diff
stringlengths
41
2.03M
msg
stringlengths
1
1.5k
repo
stringlengths
5
40
sha
stringlengths
40
40
time
stringlengths
20
20
mmm a / test / test_torch . py <nl> ppp b / test / test_torch . py <nl> <nl> TEST_LIBROSA , TEST_WITH_ROCM , run_tests , skipIfNoLapack , suppress_warnings , \ <nl> IS_WINDOWS , NO_MULTIPROCESSING_SPAWN , do_test_dtypes , do_test_empty_full , \ <nl> IS_SANDCASTLE , load_tests , slowTest , skipCUDANonDefaultStreamIf , skipCUDAMemoryLeakCheckIf , \ <nl> - BytesIOContext , skipIfRocm , torch_to_numpy_dtype_dict , skipIfNoSciPy <nl> + BytesIOContext , skipIfRocm , torch_to_numpy_dtype_dict , skipIfNoSciPy , IS_MACOS <nl> from multiprocessing . reduction import ForkingPickler <nl> from torch . testing . _internal . common_device_type import instantiate_device_type_tests , \ <nl> skipCPUIfNoLapack , skipCPUIfNoMkl , skipCUDAIfNoMagma , skipCUDAIfRocm , skipCUDAIfNotRocm , onlyCUDA , onlyCPU , \ <nl> def _float_to_int_conversion_helper ( self , vals , device , dtype ) : <nl> # errors with UBSAN . These casts are deliberate in PyTorch , however , and <nl> # NumPy has the same behavior . <nl> @ onlyOnCPUAndCUDA <nl> + @ unittest . skipIf ( IS_MACOS , " Test is broken on MacOS , see https : / / github . com / pytorch / pytorch / issues / 38752 " ) <nl> @ unittest . skipIf ( not TEST_NUMPY , " NumPy not found " ) <nl> @ dtypes ( torch . bool , torch . uint8 , torch . int8 , torch . int16 , torch . int32 , torch . int64 ) <nl> def test_float_to_int_conversion_finite ( self , device , dtype ) : <nl>
Skips test_float_to_int_conversion_finite on MacOS ( )
pytorch/pytorch
7587188037fdf90c30d0debcef60dc5d183ee9f3
2020-05-20T04:56:48Z
mmm a / tensorflow / python / distribute / BUILD <nl> ppp b / tensorflow / python / distribute / BUILD <nl> cuda_py_test ( <nl> ] , <nl> python_version = " PY3 " , <nl> tags = [ <nl> + " notap " , # TODO ( b / 171355671 ) <nl> " notsan " , # TODO ( b / 151841995 ) <nl> ] , <nl> deps = [ <nl>
Disable broken failing test
tensorflow/tensorflow
fbcdf129b9f1c834e4df78a8e9b0be388c9edb3d
2020-10-21T05:16:58Z
mmm a / xbmc / video / VideoDatabase . cpp <nl> ppp b / xbmc / video / VideoDatabase . cpp <nl> int CVideoDatabase : : SetDetailsForTvShow ( const CStdString & strPath , const CVideoI <nl> <nl> / / and insert the new row <nl> CStdString sql = " update tvshow set " + GetValueString ( details , VIDEODB_ID_TV_MIN , VIDEODB_ID_TV_MAX , DbTvShowOffsets ) ; <nl> - sql + = PrepareSQL ( " where idShow = % i " , idTvShow ) ; <nl> + sql + = PrepareSQL ( " where idShow = % i " , idTvShow ) ; <nl> m_pDS - > exec ( sql . c_str ( ) ) ; <nl> <nl> CommitTransaction ( ) ; <nl> int CVideoDatabase : : SetDetailsForEpisode ( const CStdString & strFilenameAndPath , c <nl> <nl> / / and insert the new row <nl> CStdString sql = " update episode set " + GetValueString ( details , VIDEODB_ID_EPISODE_MIN , VIDEODB_ID_EPISODE_MAX , DbEpisodeOffsets ) ; <nl> - sql + = PrepareSQL ( " where idEpisode = % i " , idEpisode ) ; <nl> + sql + = PrepareSQL ( " where idEpisode = % i " , idEpisode ) ; <nl> m_pDS - > exec ( sql . c_str ( ) ) ; <nl> CommitTransaction ( ) ; <nl> <nl>
videodb : make sure there ' s a space before the " where " in the SQL queries of SetDetailsForTvShow and SetDetailsForEpisode
xbmc/xbmc
881cf26b8b1716c3ceda9a3fd7955fb88ad0c86f
2012-08-09T11:29:45Z
mmm a / src / buffer_cache / alt / alt . hpp <nl> ppp b / src / buffer_cache / alt / alt . hpp <nl> class alt_buf_lock_t { <nl> alt_snapshot_node_t * snapshot_node_ ; <nl> <nl> / / Keeps track of how many alt_buf_ { read | write } _t have been created for <nl> - / / this lock . <nl> - int access_ref_count_ ; <nl> + / / this lock , for assertion / guarantee purposes . <nl> + intptr_t access_ref_count_ ; <nl> <nl> DISABLE_COPYING ( alt_buf_lock_t ) ; <nl> } ; <nl>
Made access_ref_count_ be an intptr_t .
rethinkdb/rethinkdb
5cb7c4fc37addbad3bf5c31be1217de5ae1ecc5c
2013-12-17T02:20:50Z
mmm a / tensorflow / python / eager / BUILD <nl> ppp b / tensorflow / python / eager / BUILD <nl> py_test ( <nl> ] , <nl> ) <nl> <nl> - py_test ( <nl> + cuda_py_test ( <nl> name = " ops_test " , <nl> srcs = [ " ops_test . py " ] , <nl> - srcs_version = " PY2AND3 " , <nl> - deps = [ <nl> + additional_deps = [ <nl> " : context " , <nl> " : execute " , <nl> " : test " , <nl> + " / / third_party / py / numpy " , <nl> " / / tensorflow / python : array_ops " , <nl> " / / tensorflow / python : control_flow_ops " , <nl> " / / tensorflow / python : dtypes " , <nl> py_test ( <nl> " / / tensorflow / python : random_ops " , <nl> " / / tensorflow / python : sparse_ops " , <nl> " / / tensorflow / python : tensor_shape " , <nl> - " / / third_party / py / numpy " , <nl> ] , <nl> ) <nl> <nl> mmm a / tensorflow / python / eager / ops_test . py <nl> ppp b / tensorflow / python / eager / ops_test . py <nl> def testMatMulGPU ( self ) : <nl> three = constant_op . constant ( [ [ 3 . ] ] ) . as_gpu_tensor ( ) <nl> five = constant_op . constant ( [ [ 5 . ] ] ) . as_gpu_tensor ( ) <nl> product = math_ops . matmul ( three , five ) <nl> - self . assertEqual ( [ [ 15 . 0 ] ] , product ) <nl> + self . assertEqual ( [ [ 15 . 0 ] ] , product . numpy ( ) ) <nl> <nl> def testExecuteStringAttr ( self ) : <nl> three = constant_op . constant ( 3 . 0 ) <nl> def testInt32CPUDefault ( self ) : <nl> self . skipTest ( ' No GPUs found ' ) <nl> with context . device ( ' / gpu : 0 ' ) : <nl> r = constant_op . constant ( 1 ) + constant_op . constant ( 2 ) <nl> - self . assertEqual ( r , 3 ) <nl> + self . assertAllEqual ( r , 3 ) <nl> <nl> def testExecuteListOutputLen1 ( self ) : <nl> split_dim = constant_op . constant ( 1 ) <nl> def testOutputOnHostMemory ( self ) : <nl> # The Shape op kernel on GPU places the output in host memory . <nl> value = constant_op . constant ( [ 1 . ] ) . as_gpu_tensor ( ) <nl> shape = array_ops . shape ( value ) <nl> - self . assertEquals ( [ 1 ] , shape ) <nl> + self . assertEqual ( [ 1 ] , shape . numpy ( ) ) <nl> <nl> def testRandomUniform ( self ) : <nl> scalar_shape = constant_op . constant ( [ ] , dtype = dtypes . int32 ) <nl>
Fixes test breakage .
tensorflow/tensorflow
bc0822675598385d8068bf114b453dac52512caf
2017-10-18T18:13:03Z
mmm a / docs / LangRef . html <nl> ppp b / docs / LangRef . html <nl> < h3 id = " reserved_punctuation " > Reserved Punctuation Tokens < / h3 > <nl> < / pre > <nl> <nl> < p > These are all reserved punctuation that are lexed into tokens . Most other <nl> - punctuation is matched as < a href = " identifier " > identifiers < / a > . <nl> + punctuation is matched as < a href = " # identifier " > identifiers < / a > . <nl> < / p > <nl> <nl> < ! - - = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = - - > <nl> < h3 id = " identifier " > Identifier Tokens < / h3 > <nl> not right - bound , and an < tt > operator - binary < / tt > in either of the <nl> other two cases . <nl> < / p > <nl> + <nl> + < p > When parsing certain grammatical constructs that involve ' & lt ; ' and <nl> + ' & gt ; ' ( such as < a href = " # type - composition " > protocol composition <nl> + types < / a > ) , an < tt > operator < / tt > with a leading ' & lt ; ' or ' & gt ; ' may <nl> + be split into two or more tokens : the leading ' & lt ; ' or ' & gt ; ' and <nl> + the remainder of the token , which may be an < tt > operator < / tt > or <nl> + < tt > punctuation < / tt > token that may itself be further split . This <nl> + rule allows us to parse nested constructs such as <nl> + < code > A & lt ; B & lt ; C & gt ; & gt ; < / code > without requiring spaces between <nl> + the closing ' & gt ; ' s . < / p > <nl> + <nl> < / div > <nl> <nl> < ! - - = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = - - > <nl> mmm a / include / swift / Parse / Lexer . h <nl> ppp b / include / swift / Parse / Lexer . h <nl> class Lexer { <nl> static SourceLoc getSourceLoc ( const char * Loc ) { <nl> return SourceLoc ( llvm : : SMLoc : : getFromPointer ( Loc ) ) ; <nl> } <nl> + <nl> + / / / getTokenKind - Retrieve the token kind for the given text , which must <nl> + / / / fall within the given source buffer . <nl> + tok getTokenKind ( StringRef Text ) ; <nl> + <nl> private : <nl> void lexImpl ( ) ; <nl> void formToken ( tok Kind , const char * TokStart ) ; <nl> mmm a / lib / Parse / Lexer . cpp <nl> ppp b / lib / Parse / Lexer . cpp <nl> InFlightDiagnostic Lexer : : diagnose ( const char * Loc , Diag < > ID ) { <nl> return InFlightDiagnostic ( ) ; <nl> } <nl> <nl> + tok Lexer : : getTokenKind ( StringRef Text ) { <nl> + assert ( Text . data ( ) > = BufferStart & & Text . data ( ) < = BufferEnd & & <nl> + " Text string does not fall within lexer ' s buffer " ) ; <nl> + Lexer L ( StringRef ( BufferStart , BufferEnd - BufferStart ) , SourceMgr , Diags , <nl> + Text . data ( ) ) ; <nl> + Token Result ; <nl> + L . lex ( Result ) ; <nl> + return Result . getKind ( ) ; <nl> + } <nl> + <nl> void Lexer : : formToken ( tok Kind , const char * TokStart ) { <nl> NextToken . setToken ( Kind , StringRef ( TokStart , CurPtr - TokStart ) ) ; <nl> } <nl> mmm a / lib / Parse / Parser . cpp <nl> ppp b / lib / Parse / Parser . cpp <nl> SourceLoc Parser : : consumeStartingLess ( ) { <nl> return consumeToken ( ) ; <nl> <nl> / / Skip the starting ' < ' in the existing token . <nl> - SourceLoc Loc = Tok . getLoc ( ) ; <nl> - Tok . setText ( Tok . getText ( ) . substr ( 1 ) ) ; <nl> + SourceLoc Loc = Tok . getLoc ( ) ; <nl> + StringRef Remaining = Tok . getText ( ) . substr ( 1 ) ; <nl> + Tok . setToken ( L - > getTokenKind ( Remaining ) , Remaining ) ; <nl> return Loc ; <nl> } <nl> <nl> SourceLoc Parser : : consumeStartingGreater ( ) { <nl> <nl> / / Skip the starting ' > ' in the existing token . <nl> SourceLoc Loc = Tok . getLoc ( ) ; <nl> - Tok . setText ( Tok . getText ( ) . substr ( 1 ) ) ; <nl> + StringRef Remaining = Tok . getText ( ) . substr ( 1 ) ; <nl> + Tok . setToken ( L - > getTokenKind ( Remaining ) , Remaining ) ; <nl> return Loc ; <nl> } <nl> <nl>
When we split a token starting with ' < ' or ' > ' , make sure that the
apple/swift
35e6e5659548ded878b68feb5359259b0cd65778
2012-06-18T16:40:59Z
mmm a / brightray / browser / inspectable_web_contents_impl . cc <nl> ppp b / brightray / browser / inspectable_web_contents_impl . cc <nl> <nl> # include " content / public / browser / browser_thread . h " <nl> # include " content / public / browser / devtools_http_handler . h " <nl> # include " content / public / browser / host_zoom_map . h " <nl> - # include " content / public / browser / navigation_entry . h " <nl> # include " content / public / browser / render_frame_host . h " <nl> # include " content / public / browser / render_view_host . h " <nl> # include " net / http / http_response_headers . h " <nl> mmm a / brightray / browser / inspectable_web_contents_view_mac . h <nl> ppp b / brightray / browser / inspectable_web_contents_view_mac . h <nl> class InspectableWebContentsViewMac : public InspectableWebContentsView { <nl> void SetIsDocked ( bool docked ) override ; <nl> void SetContentsResizingStrategy ( <nl> const DevToolsContentsResizingStrategy & strategy ) override ; <nl> + void SetTitle ( const base : : string16 & title ) override ; <nl> <nl> InspectableWebContentsImpl * inspectable_web_contents ( ) { <nl> return inspectable_web_contents_ ; <nl> mmm a / brightray / browser / inspectable_web_contents_view_mac . mm <nl> ppp b / brightray / browser / inspectable_web_contents_view_mac . mm <nl> <nl> [ view_ setContentsResizingStrategy : strategy ] ; <nl> } <nl> <nl> + void InspectableWebContentsViewMac : : SetTitle ( const base : : string16 & title ) { <nl> + [ view_ setTitle : title ] ; <nl> + } <nl> + <nl> } <nl> mmm a / brightray / browser / mac / bry_inspectable_web_contents_view . h <nl> ppp b / brightray / browser / mac / bry_inspectable_web_contents_view . h <nl> using brightray : : InspectableWebContentsViewMac ; <nl> - ( BOOL ) isDevToolsVisible ; <nl> - ( void ) setIsDocked : ( BOOL ) docked ; <nl> - ( void ) setContentsResizingStrategy : ( const DevToolsContentsResizingStrategy & ) strategy ; <nl> + - ( void ) setTitle : ( const base : : string16 & ) title ; <nl> <nl> @ end <nl> mmm a / brightray / browser / mac / bry_inspectable_web_contents_view . mm <nl> ppp b / brightray / browser / mac / bry_inspectable_web_contents_view . mm <nl> <nl> <nl> # import < QuartzCore / QuartzCore . h > <nl> <nl> + # include " base / strings / sys_string_conversions . h " <nl> # include " browser / inspectable_web_contents_impl . h " <nl> # include " browser / inspectable_web_contents_view_mac . h " <nl> <nl> - ( void ) adjustSubviews { <nl> [ contentsView setFrame : [ self flipRectToNSRect : new_contents_bounds ] ] ; <nl> } <nl> <nl> + - ( void ) setTitle : ( const base : : string16 & ) title { <nl> + if ( devtools_window_ ) { <nl> + NSString * title_string = base : : SysUTF16ToNSString ( title ) ; <nl> + [ devtools_window_ setTitle : title_string ] ; <nl> + } <nl> + } <nl> + <nl> / / Creates a path whose bottom two corners are rounded . <nl> / / Caller takes ownership of the path . <nl> - ( CGPathRef ) createRoundedBottomCornersPath : ( NSSize ) size { <nl>
implement for osx
electron/electron
26f4d09b2c3bf31067c43c26fddfcb20552343cd
2015-08-07T10:54:45Z
mmm a / include / swift / SILAnalysis / CallGraph . h <nl> ppp b / include / swift / SILAnalysis / CallGraph . h <nl> class CallGraph { <nl> <nl> void markCallerEdgesOfCalleesIncomplete ( FullApplySite AI ) ; <nl> <nl> + / / / May this function bind dynamic Self at one of its call sites ? <nl> + bool mayBindDynamicSelf ( SILFunction * F ) const { <nl> + auto * Node = getCallGraphNode ( F ) ; <nl> + assert ( Node & & " Expected call graph node for function ! " ) ; <nl> + return Node - > mayBindDynamicSelf ( ) ; <nl> + } <nl> + <nl> void print ( llvm : : raw_ostream & OS ) ; <nl> void printStats ( llvm : : raw_ostream & OS ) ; <nl> void dump ( ) ; <nl> mmm a / lib / SILPasses / FunctionSignatureOpts . cpp <nl> ppp b / lib / SILPasses / FunctionSignatureOpts . cpp <nl> class FunctionAnalyzer { <nl> / / / The function that we are analyzing . <nl> SILFunction * F ; <nl> <nl> - / / / This function ' s call graph node . <nl> - CallGraphNode * FNode ; <nl> + / / / The call graph for the module . <nl> + CallGraph & CG ; <nl> <nl> / / / Did we ascertain that we can optimize this function ? <nl> bool ShouldOptimize ; <nl> class FunctionAnalyzer { <nl> <nl> FunctionAnalyzer ( llvm : : BumpPtrAllocator & Allocator , <nl> RCIdentityFunctionInfo * RCIA , <nl> - SILFunction * F , CallGraphNode * FNode ) <nl> - : Allocator ( Allocator ) , RCIA ( RCIA ) , F ( F ) , FNode ( FNode ) , <nl> + SILFunction * F , CallGraph & CG ) <nl> + : Allocator ( Allocator ) , RCIA ( RCIA ) , F ( F ) , CG ( CG ) , <nl> ShouldOptimize ( false ) , HaveModifiedSelfArgument ( false ) , ArgDescList ( ) { } <nl> <nl> / / / Analyze the given function . <nl> class FunctionAnalyzer { <nl> bool isArgumentABIRequired ( SILArgument * Arg ) { <nl> / / This implicitly asserts that a function binding dynamic self has a self <nl> / / metadata argument or object from which self metadata can be obtained . <nl> - return FNode - > mayBindDynamicSelf ( ) & & ( F - > getSelfMetadataArgument ( ) = = Arg ) ; <nl> + return CG . mayBindDynamicSelf ( F ) & & ( F - > getSelfMetadataArgument ( ) = = Arg ) ; <nl> } <nl> <nl> private : <nl> optimizeFunctionSignature ( llvm : : BumpPtrAllocator & BPA , <nl> RCIdentityFunctionInfo * RCIA , <nl> SILFunction * F , <nl> CallGraph & CG , <nl> - CallGraphNode * FNode , <nl> const llvm : : SmallPtrSetImpl < CallGraphEdge * > & CallSites , <nl> bool CallerSetIsComplete , <nl> std : : vector < SILFunction * > & DeadFunctions ) { <nl> optimizeFunctionSignature ( llvm : : BumpPtrAllocator & BPA , <nl> llvm : : SmallVector < ArgumentDescriptor , 8 > Arguments ; <nl> <nl> / / Analyze function arguments . If there is no work to be done , exit early . <nl> - FunctionAnalyzer Analyzer ( BPA , RCIA , F , FNode ) ; <nl> + FunctionAnalyzer Analyzer ( BPA , RCIA , F , CG ) ; <nl> if ( ! Analyzer . analyze ( ) ) { <nl> DEBUG ( llvm : : dbgs ( ) < < " Has no optimizable arguments . . . " <nl> " bailing . . . \ n " ) ; <nl> class FunctionSignatureOpts : public SILModuleTransform { <nl> <nl> / / Otherwise , try to optimize the function signature of F . <nl> Changed | = optimizeFunctionSignature ( Allocator , RCIA - > get ( F ) , F , CG , <nl> - FNode , CallSites , <nl> + CallSites , <nl> CallerSetIsComplete , <nl> DeadFunctions ) ; <nl> } <nl> mmm a / lib / SILPasses / PerformanceInliner . cpp <nl> ppp b / lib / SILPasses / PerformanceInliner . cpp <nl> getEligibleFunction ( FullApplySite AI , CallGraph & CG ) { <nl> <nl> / / We don ' t support inlining a function that binds dynamic self because we <nl> / / have no mechanism to preserve the original function ' s local self metadata . <nl> - if ( CG . getCallGraphNode ( Callee ) - > mayBindDynamicSelf ( ) ) { <nl> + if ( CG . mayBindDynamicSelf ( Callee ) ) { <nl> DEBUG ( llvm : : dbgs ( ) < < " FAIL : Binding dynamic Self in " < < <nl> Callee - > getName ( ) < < " . \ n " ) ; <nl> return nullptr ; <nl>
Start hiding implementation details of the call graph .
apple/swift
c1abc4d1ffe9d5ac704d654f06ca04e307b816e2
2015-10-10T00:30:10Z
new file mode 100644 <nl> index 000000000000 . . 394ffa083a4f <nl> mmm / dev / null <nl> ppp b / jstests / aggregation / bugs / server4899 . js <nl> <nl> + / / test $ size <nl> + load ( ' jstests / aggregation / extras / utils . js ' ) ; <nl> + <nl> + c = db . server4899 ; <nl> + c . drop ( ) ; <nl> + c . save ( { arr : [ ] } ) ; <nl> + c . save ( { arr : [ 1 ] } ) ; <nl> + c . save ( { arr : [ " asdf " , " asdfasdf " ] } ) ; <nl> + c . save ( { arr : [ 1 , " asdf " , 1234 , 4 . 3 , { key : 23 } ] } ) ; <nl> + c . save ( { arr : [ 3 , [ 31 , 31 , 13 , 13 ] ] } ) ; <nl> + <nl> + result = c . aggregate ( { $ project : { _id : 0 , length : { $ size : " $ arr " } } } ) ; <nl> + assert . eq ( result . result , [ { length : 0 } , <nl> + { length : 1 } , <nl> + { length : 2 } , <nl> + { length : 5 } , <nl> + { length : 2 } ] ) ; <nl> + <nl> + c . save ( { arr : 231 } ) ; <nl> + assertErrorCode ( c , { $ project : { _id : 0 , length : { $ size : " $ arr " } } } , 17124 ) ; <nl> mmm a / src / mongo / db / pipeline / expression . cpp <nl> ppp b / src / mongo / db / pipeline / expression . cpp <nl> namespace { <nl> return " $ setUnion " ; <nl> } <nl> <nl> + / * mmmmmmmmmmmmmmmmmmmmm - - ExpressionSize mmmmmmmmmmmmmmmmmmmmmmmmmmm - * / <nl> + <nl> + Value ExpressionSize : : evaluateInternal ( const Variables & vars ) const { <nl> + Value array = vpOperand [ 0 ] - > evaluateInternal ( vars ) ; <nl> + <nl> + uassert ( 17124 , str : : stream ( ) < < " The argument to $ size must be an Array , but was of type : " <nl> + < < typeName ( array . getType ( ) ) , <nl> + array . getType ( ) = = Array ) ; <nl> + return Value : : createIntOrLong ( array . getArray ( ) . size ( ) ) ; <nl> + } <nl> + <nl> + REGISTER_EXPRESSION ( " $ size " , ExpressionSize : : parse ) ; <nl> + const char * ExpressionSize : : getOpName ( ) const { <nl> + return " $ size " ; <nl> + } <nl> + <nl> / * mmmmmmmmmmmmmmmmmmmmm - - ExpressionStrcasecmp mmmmmmmmmmmmmmmmmmmmmmmmmmm - * / <nl> <nl> Value ExpressionStrcasecmp : : evaluateInternal ( const Variables & vars ) const { <nl> mmm a / src / mongo / db / pipeline / expression . h <nl> ppp b / src / mongo / db / pipeline / expression . h <nl> namespace mongo { <nl> } ; <nl> <nl> <nl> + class ExpressionSize : public ExpressionFixedArity < ExpressionSize , 1 > { <nl> + public : <nl> + / / virtuals from ExpressionNary <nl> + virtual Value evaluateInternal ( const Variables & vars ) const ; <nl> + virtual const char * getOpName ( ) const ; <nl> + } ; <nl> + <nl> + <nl> class ExpressionStrcasecmp : public ExpressionFixedArity < ExpressionStrcasecmp , 2 > { <nl> public : <nl> / / virtuals from ExpressionNary <nl>
SERVER - 4899 $ size for aggregation
mongodb/mongo
abb240549a0174f52d1ee18a8866e0ad65a10881
2013-09-09T18:04:00Z
mmm a / Source / ComputationNetworkLib / NonlinearityNodes . h <nl> ppp b / Source / ComputationNetworkLib / NonlinearityNodes . h <nl> class ClipByValueNode : public ComputationNode < ElemType > , public NumInputs < 3 > <nl> virtual void / * ComputationNode : : * / ForwardProp ( const FrameRange & fr ) override <nl> { <nl> size_t rank = DetermineElementwiseTensorRank ( ) ; <nl> - auto result = ValueTensorFor ( rank , fr ) ; <nl> + auto result = ValueTensorFor ( rank , fr ) ; <nl> auto input0 = Input ( 0 ) - > ValueTensorFor ( rank , fr . AllowBroadcast ( ) ) ; <nl> auto input1 = Input ( 1 ) - > ValueTensorFor ( rank , fr . AllowBroadcast ( ) ) ; <nl> auto input2 = Input ( 2 ) - > ValueTensorFor ( rank , fr . AllowBroadcast ( ) ) ; <nl> class ClipByValueNode : public ComputationNode < ElemType > , public NumInputs < 3 > <nl> auto input = Input ( inputIndex ) - > ValueTensorFor ( rank , fr . AllowBroadcast ( ) ) ; <nl> auto output = ValueTensorFor ( rank , fr . AllowBroadcast ( ) ) ; <nl> <nl> - / / if reduction then mask the respective input ( s ) ( zero out the gaps ) <nl> - if ( Input ( inputIndex ) - > ReducesInTimeWrt ( shared_from_this ( ) ) ) <nl> - MaskMissingGradientColumnsToZero ( fr ) ; <nl> - if ( Input ( inputIndex ) - > ReducesInTimeWrt ( Input ( 1 - inputIndex ) ) ) <nl> - Input ( 1 - inputIndex ) - > MaskMissingValueColumnsToZero ( fr ) ; <nl> - <nl> inputGradient . AddElementwiseProductWithClipByValueDerivativeOf ( gradient , input , output ) ; <nl> } <nl> + <nl> + virtual void / * ComputationNodeBase : : * / Validate ( bool isFinalValidationPass ) override <nl> + { <nl> + / / this assumes that Input ( 1 ) and Input ( 2 ) are constants <nl> + assert ( m_inputs . size ( ) = = 3 ) ; <nl> + ComputationNodeBase : : Validate ( isFinalValidationPass ) ; <nl> + InferMBLayoutFromInputsForStandardCase ( isFinalValidationPass ) ; <nl> + SetDims ( Input ( 0 ) ) ; <nl> + } <nl> } ; <nl> <nl> template class ClipByValueNode < float > ; <nl>
added required Validate ( ) method - - specifically where we see the min and max values as constants
microsoft/CNTK
f649d39f81145067f5b6dfea3a3baf3169614f01
2016-04-25T10:07:15Z
mmm a / docs / RequestEvaluator . md <nl> ppp b / docs / RequestEvaluator . md <nl> Until then , the request - evaluator lives in a compiler that has mutable ASTs , and <nl> The request - evaluator is relatively new to the Swift compiler , having been introduced in mid - 2018 . There are a number of improvements that can be made to the evaluator itself and how it is used in the compiler : <nl> <nl> * The evaluator uses a ` DenseMap < AnyRequest , AnyValue > ` as its cache : we can almost certainly do better with per - request - kind caches that don ' t depend on so much type erasure . <nl> - * The stack of active requests uses a ` SetVector < AnyRequest > ` : we can almost certainly do better with some kind of heterogeneous on - stack representation that only realizes ` AnyRequest ` instances in the failure cases ( e . g . , to diagnose a cycle ) . <nl> * Explore how best to cache data structures in the evaluator . For example , caching ` std : : vector < T > ` or ` std : : string ` implies that we ' ll make copies of the underlying data structure each time we access the data . Could we automatically intern the data into an allocation arena owned by the evaluator , and vend ` ArrayRef < T > ` and ` StringRef ` to clients instead ? <nl> * Cycle diagnostics are far too complicated and produce very poor results . Consider replacing the current ` diagnoseCycle ` / ` noteCycleStep ` scheme with a single method that produces summary information ( e . g . , a short summary string + source location information ) and provides richer diagnostics from that string . <nl> * The ` isCached ( ) ` check to determine whether a specific instance of a request is worth caching may be at the wrong level , because one generally has to duplicate effort ( or worse , code ! ) to make the decision in ` isCached ( ) ` . Consider whether the ` evaluator ( ) ` function could return something special to say " produce this value without caching " vs . the normal " produce this value with caching " . <nl>
Merge pull request from CodaFi / mission - accomplished
apple/swift
b6bcd854af573f389844ce06cf3ecdd984412ec2
2020-03-28T19:25:47Z
mmm a / cores / esp8266 / core_esp8266_main . cpp <nl> ppp b / cores / esp8266 / core_esp8266_main . cpp <nl> static void do_global_ctors ( void ) { <nl> extern " C " void __gdb_init ( ) { } <nl> extern " C " void gdb_init ( void ) __attribute__ ( ( weak , alias ( " __gdb_init " ) ) ) ; <nl> <nl> + extern " C " void __gdb_do_break ( ) { } <nl> + extern " C " void gdb_do_break ( void ) __attribute__ ( ( weak , alias ( " __gdb_do_break " ) ) ) ; <nl> + <nl> void init_done ( ) { <nl> system_set_os_print ( 1 ) ; <nl> gdb_init ( ) ; <nl> mmm a / cores / esp8266 / core_esp8266_postmortem . c <nl> ppp b / cores / esp8266 / core_esp8266_postmortem . c <nl> <nl> # include " cont . h " <nl> <nl> extern void __real_system_restart_local ( ) ; <nl> + extern void gdb_do_break ( ) ; <nl> + <nl> extern cont_t g_cont ; <nl> <nl> static const char * s_panic_file = 0 ; <nl> void __assert_func ( const char * file , int line , const char * func , const char * wha <nl> s_panic_file = file ; <nl> s_panic_line = line ; <nl> s_panic_func = func ; <nl> + gdb_do_break ( ) ; <nl> } <nl> <nl> void __panic_func ( const char * file , int line , const char * func ) { <nl> s_panic_file = file ; <nl> s_panic_line = line ; <nl> s_panic_func = func ; <nl> + gdb_do_break ( ) ; <nl> abort ( ) ; <nl> } <nl> + <nl> mmm a / libraries / GDBStub / src / internal / gdbstub . c <nl> ppp b / libraries / GDBStub / src / internal / gdbstub . c <nl> void ATTR_GDBINIT gdbstub_init ( ) { <nl> # endif <nl> } <nl> <nl> + void ATTR_GDBFN gdbstub_do_break_wrapper ( ) { <nl> + gdbstub_do_break ( ) ; <nl> + } <nl> + <nl> + extern void gdb_do_break ( ) __attribute__ ( ( weak , alias ( " gdbstub_do_break_wrapper " ) ) ) ; <nl> extern void gdb_init ( ) __attribute__ ( ( weak , alias ( " gdbstub_init " ) ) ) ; <nl>
If GDBStub library is used , break into gdb on assert and panic
esp8266/Arduino
542b05e5436297456bff4dd2d84ef03d76f8d8b2
2016-05-10T13:30:53Z
mmm a / javascript / i18n / phonenumbers / phonenumberutil_test . js <nl> ppp b / javascript / i18n / phonenumbers / phonenumberutil_test . js <nl> function testParseExtensions ( ) { <nl> ruWithExtension . setNationalNumber ( 4232022511 ) ; <nl> ruWithExtension . setExtension ( ' 100 ' ) ; <nl> assertTrue ( ruWithExtension . equals ( <nl> - phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11 , доб . 100 ' , <nl> - RegionCode . RU ) ) ) ; <nl> + phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11 , доб . 100 ' , RegionCode . RU ) ) ) ; <nl> assertTrue ( ruWithExtension . equals ( <nl> - phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11 доб . 100 ' , <nl> - RegionCode . RU ) ) ) ; <nl> + phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11 доб . 100 ' , RegionCode . RU ) ) ) ; <nl> assertTrue ( ruWithExtension . equals ( <nl> - phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11 , доб 100 ' , <nl> - RegionCode . RU ) ) ) ; <nl> + phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11 , доб 100 ' , RegionCode . RU ) ) ) ; <nl> assertTrue ( ruWithExtension . equals ( <nl> - phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11 доб 100 ' , <nl> - RegionCode . RU ) ) ) ; <nl> + phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11 доб 100 ' , RegionCode . RU ) ) ) ; <nl> assertTrue ( ruWithExtension . equals ( <nl> - phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11доб100 ' , <nl> - RegionCode . RU ) ) ) ; <nl> + phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11доб100 ' , RegionCode . RU ) ) ) ; <nl> / / Testing in unicode format <nl> assertTrue ( ruWithExtension . equals ( <nl> phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11 , \ u0434 \ u043E \ u0431 . 100 ' , <nl> RegionCode . RU ) ) ) ; <nl> / / In upper case <nl> assertTrue ( ruWithExtension . equals ( <nl> - phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11ДОБ100 ' , <nl> - RegionCode . RU ) ) ) ; <nl> + phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11ДОБ100 ' , RegionCode . RU ) ) ) ; <nl> assertTrue ( ruWithExtension . equals ( <nl> - phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11 \ u0414 \ u041E \ u0411100 ' , <nl> - RegionCode . RU ) ) ) ; <nl> + phoneUtil . parse ( ' 8 ( 423 ) 202 - 25 - 11 \ u0414 \ u041E \ u0411100 ' , RegionCode . RU ) ) ) ; <nl> <nl> / / Test that if a number has two extensions specified , we ignore the second . <nl> / * * @ type { i18n . phonenumbers . PhoneNumber } * / <nl> function testIsNumberMatchMatches ( ) { <nl> phoneUtil . isNumberMatch ( ' + 64 3 331 - 6005 ext . 1234 ' , <nl> ' + 6433316005 ; 1234 ' ) ) ; <nl> assertEquals ( i18n . phonenumbers . PhoneNumberUtil . MatchType . EXACT_MATCH , <nl> - phoneUtil . isNumberMatch ( <nl> - ' + 7 423 202 - 25 - 11 ext 100 ' , <nl> - ' + 7 4232022511 доб . 100 ' ) ) ; <nl> + phoneUtil . isNumberMatch ( ' + 7 423 202 - 25 - 11 ext 100 ' , <nl> + ' + 7 4232022511 доб . 100 ' ) ) ; <nl> / / Test proto buffers . <nl> assertEquals ( i18n . phonenumbers . PhoneNumberUtil . MatchType . EXACT_MATCH , <nl> phoneUtil . isNumberMatch ( NZ_NUMBER , ' + 6403 331 6005 ' ) ) ; <nl>
Remove special chars in the diffs and make alignment consistent ( )
google/libphonenumber
c568572a5a159c7d43d496f7cbd57367d55a82cf
2018-08-29T06:40:57Z
mmm a / src / qt / receiverequestdialog . cpp <nl> ppp b / src / qt / receiverequestdialog . cpp <nl> <nl> # include < QMimeData > <nl> # include < QMouseEvent > <nl> # include < QPixmap > <nl> + # include < QMenu > <nl> # if QT_VERSION < 0x050000 <nl> # include < QUrl > <nl> # endif <nl> <nl> # endif <nl> <nl> QRImageWidget : : QRImageWidget ( QWidget * parent ) : <nl> - QLabel ( parent ) <nl> + QLabel ( parent ) , contextMenu ( 0 ) <nl> { <nl> - setContextMenuPolicy ( Qt : : ActionsContextMenu ) ; <nl> - <nl> + contextMenu = new QMenu ( ) ; <nl> QAction * saveImageAction = new QAction ( tr ( " & Save Image . . . " ) , this ) ; <nl> connect ( saveImageAction , SIGNAL ( triggered ( ) ) , this , SLOT ( saveImage ( ) ) ) ; <nl> - addAction ( saveImageAction ) ; <nl> + contextMenu - > addAction ( saveImageAction ) ; <nl> QAction * copyImageAction = new QAction ( tr ( " & Copy Image " ) , this ) ; <nl> connect ( copyImageAction , SIGNAL ( triggered ( ) ) , this , SLOT ( copyImage ( ) ) ) ; <nl> - addAction ( copyImageAction ) ; <nl> + contextMenu - > addAction ( copyImageAction ) ; <nl> } <nl> <nl> QImage QRImageWidget : : exportImage ( ) <nl> { <nl> + if ( ! pixmap ( ) ) <nl> + return QImage ( ) ; <nl> return pixmap ( ) - > toImage ( ) . scaled ( EXPORT_IMAGE_SIZE , EXPORT_IMAGE_SIZE ) ; <nl> } <nl> <nl> void QRImageWidget : : mousePressEvent ( QMouseEvent * event ) <nl> { <nl> - if ( event - > button ( ) = = Qt : : LeftButton ) <nl> + if ( event - > button ( ) = = Qt : : LeftButton & & pixmap ( ) ) <nl> { <nl> event - > accept ( ) ; <nl> QMimeData * mimeData = new QMimeData ; <nl> void QRImageWidget : : mousePressEvent ( QMouseEvent * event ) <nl> <nl> void QRImageWidget : : saveImage ( ) <nl> { <nl> + if ( ! pixmap ( ) ) <nl> + return ; <nl> QString fn = GUIUtil : : getSaveFileName ( this , tr ( " Save QR Code " ) , QString ( ) , tr ( " PNG Image ( * . png ) " ) , NULL ) ; <nl> if ( ! fn . isEmpty ( ) ) <nl> { <nl> void QRImageWidget : : saveImage ( ) <nl> <nl> void QRImageWidget : : copyImage ( ) <nl> { <nl> + if ( ! pixmap ( ) ) <nl> + return ; <nl> QApplication : : clipboard ( ) - > setImage ( exportImage ( ) ) ; <nl> } <nl> <nl> + void QRImageWidget : : contextMenuEvent ( QContextMenuEvent * event ) <nl> + { <nl> + if ( ! pixmap ( ) ) <nl> + return ; <nl> + contextMenu - > exec ( event - > globalPos ( ) ) ; <nl> + } <nl> + <nl> ReceiveRequestDialog : : ReceiveRequestDialog ( QWidget * parent ) : <nl> QDialog ( parent ) , <nl> ui ( new Ui : : ReceiveRequestDialog ) , <nl> mmm a / src / qt / receiverequestdialog . h <nl> ppp b / src / qt / receiverequestdialog . h <nl> namespace Ui { <nl> class ReceiveRequestDialog ; <nl> } <nl> class OptionsModel ; <nl> + QT_BEGIN_NAMESPACE <nl> + class QMenu ; <nl> + QT_END_NAMESPACE <nl> <nl> / * Label widget for QR code . This image can be dragged , dropped , copied and saved <nl> * to disk . <nl> public slots : <nl> <nl> protected : <nl> virtual void mousePressEvent ( QMouseEvent * event ) ; <nl> + virtual void contextMenuEvent ( QContextMenuEvent * event ) ; <nl> + <nl> + private : <nl> + QMenu * contextMenu ; <nl> } ; <nl> <nl> class ReceiveRequestDialog : public QDialog <nl>
ui : Check for ! pixmap ( ) before trying to export QR code
bitcoin/bitcoin
9d558e1c18a29bbccec802829f9b8b65fb4101a1
2014-05-07T06:42:12Z
mmm a / lib / IRGen / IRGen . cpp <nl> ppp b / lib / IRGen / IRGen . cpp <nl> static std : : unique_ptr < llvm : : Module > performIRGeneration ( IRGenOptions & Opts , <nl> PMBuilder . LoopVectorize = true ; <nl> } else { <nl> PMBuilder . OptLevel = 0 ; <nl> + PMBuilder . Inliner = llvm : : createAlwaysInlinerPass ( / * insert lifetime * / false ) ; <nl> } <nl> <nl> / / If the optimizer is enabled , we run the ARCOpt pass in the scalar optimizer <nl> mmm a / test / IRGen / Inputs / usr / include / Gizmo . h <nl> ppp b / test / IRGen / Inputs / usr / include / Gizmo . h <nl> static inline int innerZero ( void ) { return 0 ; } <nl> static inline int zero ( void ) { return innerZero ( ) ; } <nl> static inline int wrappedZero ( void ) { return zero ( ) ; } <nl> <nl> + static inline int alwaysInlineNumber ( void ) __attribute__ ( ( always_inline ) ) { <nl> + return 17 ; <nl> + } <nl> + <nl> extern int getInt ( void ) ; <nl> static inline int wrappedGetInt ( void ) { return getInt ( ) ; } <nl> <nl> mmm a / test / IRGen / clang_inline . swift <nl> ppp b / test / IRGen / clang_inline . swift <nl> func testExtern ( ) - > CInt { <nl> return wrappedGetInt ( ) <nl> } <nl> <nl> - / / CHECK : define internal i32 @ innerZero ( ) # 2 { <nl> - / / CHECK : declare i32 @ getInt ( ) # 3 <nl> + / / CHECK : define hidden i32 @ _TF12clang_inline16testAlwaysInlineFT_VSs5Int32 ( ) [ [ SSP : # [ 0 - 9 ] + ] ] { <nl> + / / CHECK - NOT : @ alwaysInlineNumber <nl> + / / CHECK : ret i32 17 <nl> + / / CHECK - NOT : @ alwaysInlineNumber <nl> + func testAlwaysInline ( ) - > CInt { <nl> + return alwaysInlineNumber ( ) <nl> + } <nl> + <nl> + / / CHECK - NOT : @ alwaysInlineNumber <nl> + / / CHECK : define internal i32 @ innerZero ( ) [ [ INNER_ZERO_ATTR : # [ 0 - 9 ] + ] ] { <nl> + / / CHECK : declare i32 @ getInt ( ) [ [ GET_INT_ATTR : # [ 0 - 9 ] + ] ] <nl> + / / CHECK - NOT : @ alwaysInlineNumber <nl> + <nl> + / / CHECK : attributes [ [ SSP ] ] = { ssp } <nl> + / / CHECK : attributes [ [ INNER_ZERO_ATTR ] ] = { inlinehint nounwind ssp <nl> + / / CHECK : attributes [ [ GET_INT_ATTR ] ] = { <nl>
IRGen : Install the AlwaysInliner pass at - O0 .
apple/swift
056f55fd478ea72f721347b6b5eff63826ebb21b
2014-12-08T22:07:30Z
mmm a / rpm / init . d - mongod <nl> ppp b / rpm / init . d - mongod <nl> CONFIGFILE = " / etc / mongod . conf " <nl> OPTIONS = " - f $ CONFIGFILE " <nl> SYSCONFIG = " / etc / sysconfig / mongod " <nl> <nl> - # FIXME : 1 . 9 . x has a - - shutdown flag that parses the config file and <nl> - # shuts down the correct running pid , but that ' s unavailable in 1 . 8 <nl> - # for now . This can go away when this script stops supporting 1 . 8 . <nl> DBPATH = ` awk - F ' [ : = ] ' - v IGNORECASE = 1 ' / ^ [ [ : blank : ] ] * dbpath [ [ : blank : ] ] * [ : = ] [ [ : blank : ] ] * / { print $ 2 } ' " $ CONFIGFILE " | tr - d ' [ : blank : ] ' ` <nl> PIDFILEPATH = ` awk - F ' [ : = ] ' - v IGNORECASE = 1 ' / ^ [ [ : blank : ] ] * pidfilepath [ [ : blank : ] ] * [ : = ] [ [ : blank : ] ] * / { print $ 2 } ' " $ CONFIGFILE " | tr - d ' [ : blank : ] ' ` <nl> PIDDIR = ` dirname $ PIDFILEPATH ` <nl>
SERVER - 15114 Remove misleading init script comment
mongodb/mongo
65be70d436feaff4de13f3508e5115eccc14056f
2014-09-02T20:40:03Z
mmm a / trunk / src / kernel / srs_kernel_error . hpp <nl> ppp b / trunk / src / kernel / srs_kernel_error . hpp <nl> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . <nl> # define ERROR_HTTP_RESPONSE_EOF 4025 <nl> # define ERROR_HTTP_INVALID_CHUNK_HEADER 4026 <nl> # define ERROR_AVC_NALU_UEV 4027 <nl> + # define ERROR_AAC_BYTES_INVALID 4028 <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / user - define error . <nl> mmm a / trunk / src / kernel / srs_kernel_utility . cpp <nl> ppp b / trunk / src / kernel / srs_kernel_utility . cpp <nl> bool srs_string_starts_with ( string str , string flag ) <nl> return str . find ( flag ) = = 0 ; <nl> } <nl> <nl> + bool srs_string_contains ( string str , string flag ) <nl> + { <nl> + return str . find ( flag ) ! = string : : npos ; <nl> + } <nl> + <nl> int srs_do_create_dir_recursively ( string dir ) <nl> { <nl> int ret = ERROR_SUCCESS ; <nl> string srs_path_dirname ( string path ) <nl> return dirname ; <nl> } <nl> <nl> + string srs_path_basename ( string path ) <nl> + { <nl> + std : : string dirname = path ; <nl> + size_t pos = string : : npos ; <nl> + <nl> + if ( ( pos = dirname . rfind ( " / " ) ) ! = string : : npos ) { <nl> + / / the basename ( " / " ) is " / " <nl> + if ( dirname . length ( ) = = 1 ) { <nl> + return dirname ; <nl> + } <nl> + dirname = dirname . substr ( pos + 1 ) ; <nl> + } <nl> + <nl> + return dirname ; <nl> + } <nl> + <nl> bool srs_avc_startswith_annexb ( SrsStream * stream , int * pnb_start_code ) <nl> { <nl> char * bytes = stream - > data ( ) + stream - > pos ( ) ; <nl> mmm a / trunk / src / kernel / srs_kernel_utility . hpp <nl> ppp b / trunk / src / kernel / srs_kernel_utility . hpp <nl> extern std : : string srs_string_remove ( std : : string str , std : : string remove_chars ) ; <nl> extern bool srs_string_ends_with ( std : : string str , std : : string flag ) ; <nl> / / whether string starts with <nl> extern bool srs_string_starts_with ( std : : string str , std : : string flag ) ; <nl> + / / whether string contains with <nl> + extern bool srs_string_contains ( std : : string str , std : : string flag ) ; <nl> <nl> / / create dir recursively <nl> extern int srs_create_dir_recursively ( std : : string dir ) ; <nl> extern int srs_create_dir_recursively ( std : : string dir ) ; <nl> extern bool srs_path_exists ( std : : string path ) ; <nl> / / get the dirname of path <nl> extern std : : string srs_path_dirname ( std : : string path ) ; <nl> + / / get the basename of path <nl> + extern std : : string srs_path_basename ( std : : string path ) ; <nl> <nl> / * * <nl> * whether stream starts with the avc NALU in " AnnexB " <nl> mmm a / trunk / src / main / srs_main_ingest_hls . cpp <nl> ppp b / trunk / src / main / srs_main_ingest_hls . cpp <nl> int main ( int argc , char * * argv ) <nl> return proxy_hls2rtmp ( in_hls_url , out_rtmp_url ) ; <nl> } <nl> <nl> + class ISrsAacHandler <nl> + { <nl> + public : <nl> + / * * <nl> + * handle the aac frame , which in ADTS format ( starts with FFFx ) . <nl> + * @ param duration the duration in seconds of frames . <nl> + * / <nl> + virtual int on_aac_frame ( char * frame , int frame_size , double duration ) = 0 ; <nl> + } ; <nl> + <nl> / / the context to ingest hls stream . <nl> class SrsIngestSrsInput <nl> { <nl> class SrsIngestSrsInput <nl> / * * <nl> * parse the ts and use hanler to process the message . <nl> * / <nl> - virtual int parse ( ISrsTsHandler * handler ) ; <nl> + virtual int parse ( ISrsTsHandler * ts , ISrsAacHandler * aac ) ; <nl> private : <nl> + / * * <nl> + * parse the ts pieces body . <nl> + * / <nl> + virtual int parseAac ( ISrsAacHandler * handler , char * body , int nb_body , double duration ) ; <nl> + virtual int parseTs ( ISrsTsHandler * handler , char * body , int nb_body ) ; <nl> + / * * <nl> + * parse the m3u8 specified by url . <nl> + * / <nl> + virtual int parseM3u8 ( SrsHttpUri * url , double & td , double & duration ) ; <nl> / * * <nl> * find the ts piece by its url . <nl> * / <nl> int SrsIngestSrsInput : : connect ( ) <nl> st_usleep ( ( next_connect_time - now ) * 1000 ) ; <nl> } <nl> <nl> + / / set all ts to dirty . <nl> + dirty_all_ts ( ) ; <nl> + <nl> + bool fresh_m3u8 = pieces . empty ( ) ; <nl> + double td = 0 . 0 ; <nl> + double duration = 0 . 0 ; <nl> + if ( ( ret = parseM3u8 ( in_hls , td , duration ) ) ! = ERROR_SUCCESS ) { <nl> + return ret ; <nl> + } <nl> + <nl> + / / fetch all ts . <nl> + fetch_all_ts ( fresh_m3u8 ) ; <nl> + <nl> + / / remove all dirty ts . <nl> + remove_dirty ( ) ; <nl> + <nl> + srs_trace ( " fetch m3u8 ok , td = % . 2f , duration = % . 2f , pieces = % d " , td , duration , pieces . size ( ) ) ; <nl> + <nl> + return ret ; <nl> + } <nl> + <nl> + int SrsIngestSrsInput : : parse ( ISrsTsHandler * ts , ISrsAacHandler * aac ) <nl> + { <nl> + int ret = ERROR_SUCCESS ; <nl> + <nl> + for ( int i = 0 ; i < ( int ) pieces . size ( ) ; i + + ) { <nl> + SrsTsPiece * tp = pieces . at ( i ) ; <nl> + <nl> + / / sent only once . <nl> + if ( tp - > sent ) { <nl> + continue ; <nl> + } <nl> + tp - > sent = true ; <nl> + <nl> + if ( tp - > body . empty ( ) ) { <nl> + continue ; <nl> + } <nl> + <nl> + srs_trace ( " proxy the ts to rtmp , ts = % s , duration = % . 2f " , tp - > url . c_str ( ) , tp - > duration ) ; <nl> + <nl> + if ( srs_string_ends_with ( tp - > url , " . ts " ) ) { <nl> + if ( ( ret = parseTs ( ts , ( char * ) tp - > body . data ( ) , ( int ) tp - > body . length ( ) ) ) ! = ERROR_SUCCESS ) { <nl> + return ret ; <nl> + } <nl> + } else if ( srs_string_ends_with ( tp - > url , " . aac " ) ) { <nl> + if ( ( ret = parseAac ( aac , ( char * ) tp - > body . data ( ) , ( int ) tp - > body . length ( ) , tp - > duration ) ) ! = ERROR_SUCCESS ) { <nl> + return ret ; <nl> + } <nl> + } else { <nl> + srs_warn ( " ignore unkown piece % s " , tp - > url . c_str ( ) ) ; <nl> + } <nl> + } <nl> + <nl> + return ret ; <nl> + } <nl> + <nl> + int SrsIngestSrsInput : : parseTs ( ISrsTsHandler * handler , char * body , int nb_body ) <nl> + { <nl> + int ret = ERROR_SUCCESS ; <nl> + <nl> + / / use stream to parse ts packet . <nl> + int nb_packet = ( int ) nb_body / SRS_TS_PACKET_SIZE ; <nl> + for ( int i = 0 ; i < nb_packet ; i + + ) { <nl> + char * p = ( char * ) body + ( i * SRS_TS_PACKET_SIZE ) ; <nl> + if ( ( ret = stream - > initialize ( p , SRS_TS_PACKET_SIZE ) ) ! = ERROR_SUCCESS ) { <nl> + return ret ; <nl> + } <nl> + <nl> + / / process each ts packet <nl> + if ( ( ret = context - > decode ( stream , handler ) ) ! = ERROR_SUCCESS ) { <nl> + / / when peer closed , must interrupt parse and reconnect . <nl> + if ( srs_is_client_gracefully_close ( ret ) ) { <nl> + srs_warn ( " interrupt parse for peer closed . ret = % d " , ret ) ; <nl> + return ret ; <nl> + } <nl> + <nl> + srs_warn ( " mpegts : ignore parse ts packet failed . ret = % d " , ret ) ; <nl> + continue ; <nl> + } <nl> + srs_info ( " mpegts : parse ts packet completed " ) ; <nl> + } <nl> + srs_info ( " mpegts : parse udp packet completed " ) ; <nl> + <nl> + return ret ; <nl> + } <nl> + <nl> + int SrsIngestSrsInput : : parseAac ( ISrsAacHandler * handler , char * body , int nb_body , double duration ) <nl> + { <nl> + int ret = ERROR_SUCCESS ; <nl> + <nl> + if ( ( ret = stream - > initialize ( body , nb_body ) ) ! = ERROR_SUCCESS ) { <nl> + return ret ; <nl> + } <nl> + <nl> + / / atleast 2bytes . <nl> + if ( ! stream - > require ( 3 ) ) { <nl> + ret = ERROR_AAC_BYTES_INVALID ; <nl> + srs_error ( " invalid aac , atleast 3bytes . ret = % d " , ret ) ; <nl> + return ret ; <nl> + } <nl> + <nl> + u_int8_t id0 = ( u_int8_t ) body [ 0 ] ; <nl> + u_int8_t id1 = ( u_int8_t ) body [ 1 ] ; <nl> + u_int8_t id2 = ( u_int8_t ) body [ 2 ] ; <nl> + <nl> + / / skip ID3 . <nl> + if ( id0 = = 0x49 & & id1 = = 0x44 & & id2 = = 0x33 ) { <nl> + / * char id3 [ ] = { <nl> + ( char ) 0x49 , ( char ) 0x44 , ( char ) 0x33 , / / ID3 <nl> + ( char ) 0x03 , ( char ) 0x00 , / / version <nl> + ( char ) 0x00 , / / flags <nl> + ( char ) 0x00 , ( char ) 0x00 , ( char ) 0x00 , ( char ) 0x0a , / / size <nl> + <nl> + ( char ) 0x00 , ( char ) 0x00 , ( char ) 0x00 , ( char ) 0x00 , / / FrameID <nl> + ( char ) 0x00 , ( char ) 0x00 , ( char ) 0x00 , ( char ) 0x00 , / / FrameSize <nl> + ( char ) 0x00 , ( char ) 0x00 / / Flags <nl> + } ; * / <nl> + / / atleast 10 bytes . <nl> + if ( ! stream - > require ( 10 ) ) { <nl> + ret = ERROR_AAC_BYTES_INVALID ; <nl> + srs_error ( " invalid aac ID3 , atleast 10bytes . ret = % d " , ret ) ; <nl> + return ret ; <nl> + } <nl> + <nl> + / / ignore ID3 + version + flag . <nl> + stream - > skip ( 6 ) ; <nl> + / / read the size of ID3 . <nl> + u_int32_t nb_id3 = stream - > read_4bytes ( ) ; <nl> + <nl> + / / read body of ID3 <nl> + if ( ! stream - > require ( nb_id3 ) ) { <nl> + ret = ERROR_AAC_BYTES_INVALID ; <nl> + srs_error ( " invalid aac ID3 body , required % dbytes . ret = % d " , nb_id3 , ret ) ; <nl> + return ret ; <nl> + } <nl> + stream - > skip ( nb_id3 ) ; <nl> + } <nl> + <nl> + char * frame = body + stream - > pos ( ) ; <nl> + int frame_size = nb_body - stream - > pos ( ) ; <nl> + return handler - > on_aac_frame ( frame , frame_size , duration ) ; <nl> + } <nl> + <nl> + int SrsIngestSrsInput : : parseM3u8 ( SrsHttpUri * url , double & td , double & duration ) <nl> + { <nl> + int ret = ERROR_SUCCESS ; <nl> + <nl> SrsHttpClient client ; <nl> - srs_trace ( " parse input hls % s " , in_hls - > get_url ( ) ) ; <nl> + srs_trace ( " parse input hls % s " , url - > get_url ( ) ) ; <nl> <nl> - if ( ( ret = client . initialize ( in_hls - > get_host ( ) , in_hls - > get_port ( ) ) ) ! = ERROR_SUCCESS ) { <nl> + if ( ( ret = client . initialize ( url - > get_host ( ) , url - > get_port ( ) ) ) ! = ERROR_SUCCESS ) { <nl> srs_error ( " connect to server failed . ret = % d " , ret ) ; <nl> return ret ; <nl> } <nl> <nl> SrsHttpMessage * msg = NULL ; <nl> - if ( ( ret = client . get ( in_hls - > get_path ( ) , " " , & msg ) ) ! = ERROR_SUCCESS ) { <nl> - srs_error ( " HTTP GET % s failed . ret = % d " , in_hls - > get_url ( ) , ret ) ; <nl> + if ( ( ret = client . get ( url - > get_path ( ) , " " , & msg ) ) ! = ERROR_SUCCESS ) { <nl> + srs_error ( " HTTP GET % s failed . ret = % d " , url - > get_url ( ) , ret ) ; <nl> return ret ; <nl> } <nl> <nl> int SrsIngestSrsInput : : connect ( ) <nl> return ret ; <nl> } <nl> <nl> - / / set all ts to dirty . <nl> - dirty_all_ts ( ) ; <nl> - <nl> std : : string ptl ; <nl> - double td = 0 . 0 ; <nl> - double duration = 0 . 0 ; <nl> - bool fresh_m3u8 = pieces . empty ( ) ; <nl> while ( ! body . empty ( ) ) { <nl> size_t pos = string : : npos ; <nl> <nl> int SrsIngestSrsInput : : connect ( ) <nl> break ; <nl> } <nl> <nl> + / / # EXT - X - STREAM - INF : PROGRAM - ID = 1 , BANDWIDTH = 73207 , CODECS = " mp4a . 40 . 2 " <nl> + if ( srs_string_starts_with ( line , " # EXT - X - STREAM - INF : " ) ) { <nl> + if ( ( pos = body . find ( " \ n " ) ) = = string : : npos ) { <nl> + srs_warn ( " m3u8 entry unexpected eof , inf = % s " , line . c_str ( ) ) ; <nl> + break ; <nl> + } <nl> + <nl> + std : : string m3u8_url = body . substr ( 0 , pos ) ; <nl> + body = body . substr ( pos + 1 ) ; <nl> + <nl> + if ( ! srs_string_starts_with ( m3u8_url , " http : / / " ) ) { <nl> + m3u8_url = srs_path_dirname ( url - > get_url ( ) ) + " / " + m3u8_url ; <nl> + } <nl> + srs_trace ( " parse sub m3u8 , url = % s " , m3u8_url . c_str ( ) ) ; <nl> + <nl> + if ( ( ret = url - > initialize ( m3u8_url ) ) ! = ERROR_SUCCESS ) { <nl> + return ret ; <nl> + } <nl> + <nl> + return parseM3u8 ( url , td , duration ) ; <nl> + } <nl> + <nl> / / # EXTINF : 11 . 401 , <nl> / / livestream - 5 . ts <nl> / / parse each ts entry , expect current line is inf . <nl> int SrsIngestSrsInput : : connect ( ) <nl> } <nl> } <nl> <nl> - / / fetch all ts . <nl> - fetch_all_ts ( fresh_m3u8 ) ; <nl> - <nl> - / / remove all dirty ts . <nl> - remove_dirty ( ) ; <nl> - <nl> - srs_trace ( " fetch m3u8 ok , td = % . 2f , duration = % . 2f , pieces = % d " , td , duration , pieces . size ( ) ) ; <nl> - <nl> - return ret ; <nl> - } <nl> - <nl> - int SrsIngestSrsInput : : parse ( ISrsTsHandler * handler ) <nl> - { <nl> - int ret = ERROR_SUCCESS ; <nl> - <nl> - for ( int i = 0 ; i < ( int ) pieces . size ( ) ; i + + ) { <nl> - SrsTsPiece * tp = pieces . at ( i ) ; <nl> - <nl> - / / sent only once . <nl> - if ( tp - > sent ) { <nl> - continue ; <nl> - } <nl> - tp - > sent = true ; <nl> - <nl> - if ( tp - > body . empty ( ) ) { <nl> - continue ; <nl> - } <nl> - <nl> - srs_trace ( " proxy the ts to rtmp , ts = % s , duration = % . 2f " , tp - > url . c_str ( ) , tp - > duration ) ; <nl> - <nl> - / / use stream to parse ts packet . <nl> - int nb_packet = ( int ) tp - > body . length ( ) / SRS_TS_PACKET_SIZE ; <nl> - for ( int i = 0 ; i < nb_packet ; i + + ) { <nl> - char * p = ( char * ) tp - > body . data ( ) + ( i * SRS_TS_PACKET_SIZE ) ; <nl> - if ( ( ret = stream - > initialize ( p , SRS_TS_PACKET_SIZE ) ) ! = ERROR_SUCCESS ) { <nl> - return ret ; <nl> - } <nl> - <nl> - / / process each ts packet <nl> - if ( ( ret = context - > decode ( stream , handler ) ) ! = ERROR_SUCCESS ) { <nl> - / / when peer closed , must interrupt parse and reconnect . <nl> - if ( srs_is_client_gracefully_close ( ret ) ) { <nl> - srs_warn ( " interrupt parse for peer closed . ret = % d " , ret ) ; <nl> - return ret ; <nl> - } <nl> - <nl> - srs_warn ( " mpegts : ignore parse ts packet failed . ret = % d " , ret ) ; <nl> - continue ; <nl> - } <nl> - srs_info ( " mpegts : parse ts packet completed " ) ; <nl> - } <nl> - srs_info ( " mpegts : parse udp packet completed " ) ; <nl> - } <nl> - <nl> return ret ; <nl> } <nl> <nl> int SrsIngestSrsInput : : SrsTsPiece : : fetch ( string m3u8 ) <nl> return ret ; <nl> } <nl> <nl> - size_t pos = string : : npos ; <nl> - <nl> SrsHttpClient client ; <nl> <nl> std : : string ts_url = url ; <nl> if ( ! srs_string_starts_with ( ts_url , " http : / / " ) ) { <nl> - std : : string baseurl = m3u8 ; <nl> - if ( ( pos = m3u8 . rfind ( " / " ) ) ! = string : : npos ) { <nl> - baseurl = m3u8 . substr ( 0 , pos ) ; <nl> - } <nl> - ts_url = baseurl + " / " + url ; <nl> + ts_url = srs_path_dirname ( m3u8 ) + " / " + url ; <nl> } <nl> <nl> SrsHttpUri uri ; <nl> int SrsIngestSrsInput : : SrsTsPiece : : fetch ( string m3u8 ) <nl> } <nl> <nl> / / the context to output to rtmp server <nl> - class SrsIngestSrsOutput : public ISrsTsHandler <nl> + class SrsIngestSrsOutput : virtual public ISrsTsHandler , virtual public ISrsAacHandler <nl> { <nl> private : <nl> SrsHttpUri * out_rtmp ; <nl> private : <nl> bool disconnected ; <nl> std : : multimap < int64_t , SrsTsMessage * > queue ; <nl> + int64_t raw_aac_dts ; <nl> private : <nl> SrsRequest * req ; <nl> st_netfd_t stfd ; <nl> class SrsIngestSrsOutput : public ISrsTsHandler <nl> SrsIngestSrsOutput ( SrsHttpUri * rtmp ) { <nl> out_rtmp = rtmp ; <nl> disconnected = false ; <nl> + raw_aac_dts = 0 ; <nl> <nl> req = NULL ; <nl> io = NULL ; <nl> class SrsIngestSrsOutput : public ISrsTsHandler <nl> / / interface ISrsTsHandler <nl> public : <nl> virtual int on_ts_message ( SrsTsMessage * msg ) ; <nl> + / / interface IAacHandler <nl> + public : <nl> + virtual int on_aac_frame ( char * frame , int frame_size , double duration ) ; <nl> private : <nl> + virtual int do_on_aac_frame ( SrsStream * avs , double duration ) ; <nl> virtual int parse_message_queue ( ) ; <nl> virtual int on_ts_video ( SrsTsMessage * msg , SrsStream * avs ) ; <nl> virtual int write_h264_sps_pps ( u_int32_t dts , u_int32_t pts ) ; <nl> int SrsIngestSrsOutput : : on_ts_message ( SrsTsMessage * msg ) <nl> return ret ; <nl> } <nl> <nl> + int SrsIngestSrsOutput : : on_aac_frame ( char * frame , int frame_size , double duration ) <nl> + { <nl> + int ret = ERROR_SUCCESS ; <nl> + <nl> + srs_trace ( " handle aac frames , size = % dB , duration = % . 2f , dts = % " PRId64 , frame_size , duration , raw_aac_dts ) ; <nl> + <nl> + SrsStream stream ; <nl> + if ( ( ret = stream . initialize ( frame , frame_size ) ) ! = ERROR_SUCCESS ) { <nl> + return ret ; <nl> + } <nl> + <nl> + return do_on_aac_frame ( & stream , duration ) ; <nl> + } <nl> + <nl> + int SrsIngestSrsOutput : : do_on_aac_frame ( SrsStream * avs , double duration ) <nl> + { <nl> + int ret = ERROR_SUCCESS ; <nl> + <nl> + / / ts tbn to flv tbn . <nl> + u_int32_t dts = ( u_int32_t ) raw_aac_dts ; <nl> + raw_aac_dts + = ( int64_t ) ( duration * 1000 ) ; <nl> + <nl> + / / got the next msg to calc the delta duration for each audio . <nl> + u_int32_t max_dts = dts + ( u_int32_t ) ( duration * 1000 ) ; <nl> + <nl> + / / send each frame . <nl> + while ( ! avs - > empty ( ) ) { <nl> + char * frame = NULL ; <nl> + int frame_size = 0 ; <nl> + SrsRawAacStreamCodec codec ; <nl> + if ( ( ret = aac - > adts_demux ( avs , & frame , & frame_size , codec ) ) ! = ERROR_SUCCESS ) { <nl> + return ret ; <nl> + } <nl> + <nl> + / / ignore invalid frame , <nl> + / / * atleast 1bytes for aac to decode the data . <nl> + if ( frame_size < = 0 ) { <nl> + continue ; <nl> + } <nl> + srs_info ( " mpegts : demux aac frame size = % d , dts = % d " , frame_size , dts ) ; <nl> + <nl> + / / generate sh . <nl> + if ( aac_specific_config . empty ( ) ) { <nl> + std : : string sh ; <nl> + if ( ( ret = aac - > mux_sequence_header ( & codec , sh ) ) ! = ERROR_SUCCESS ) { <nl> + return ret ; <nl> + } <nl> + aac_specific_config = sh ; <nl> + <nl> + codec . aac_packet_type = 0 ; <nl> + <nl> + if ( ( ret = write_audio_raw_frame ( ( char * ) sh . data ( ) , ( int ) sh . length ( ) , & codec , dts ) ) ! = ERROR_SUCCESS ) { <nl> + return ret ; <nl> + } <nl> + } <nl> + <nl> + / / audio raw data . <nl> + codec . aac_packet_type = 1 ; <nl> + if ( ( ret = write_audio_raw_frame ( frame , frame_size , & codec , dts ) ) ! = ERROR_SUCCESS ) { <nl> + return ret ; <nl> + } <nl> + <nl> + / / calc the delta of dts , when previous frame output . <nl> + u_int32_t delta = ( duration * 1000 ) / ( avs - > size ( ) / frame_size ) ; <nl> + dts = ( u_int32_t ) ( srs_min ( max_dts , dts + delta ) ) ; <nl> + } <nl> + <nl> + return ret ; <nl> + } <nl> + <nl> int SrsIngestSrsOutput : : parse_message_queue ( ) <nl> { <nl> int ret = ERROR_SUCCESS ; <nl> int SrsIngestSrsOutput : : on_ts_audio ( SrsTsMessage * msg , SrsStream * avs ) <nl> / / ts tbn to flv tbn . <nl> u_int32_t dts = ( u_int32_t ) ( msg - > dts / 90 ) ; <nl> <nl> - / / got the next video to calc the delta duration for each audio . <nl> + / / got the next msg to calc the delta duration for each audio . <nl> u_int32_t duration = 0 ; <nl> if ( ! queue . empty ( ) ) { <nl> SrsTsMessage * nm = queue . begin ( ) - > second ; <nl> int SrsIngestSrsOutput : : rtmp_write_packet ( char type , u_int32_t timestamp , char * <nl> } <nl> srs_assert ( msg ) ; <nl> <nl> + srs_info ( " RTMP type = % d , dts = % d , size = % d " , type , timestamp , size ) ; <nl> + <nl> / / send out encoded msg . <nl> if ( ( ret = client - > send_and_free_message ( msg , stream_id ) ) ! = ERROR_SUCCESS ) { <nl> return ret ; <nl> int SrsIngestSrsOutput : : connect ( ) <nl> if ( ! req ) { <nl> req = new SrsRequest ( ) ; <nl> <nl> - size_t pos = string : : npos ; <nl> string uri = req - > tcUrl = out_rtmp - > get_url ( ) ; <nl> <nl> / / tcUrl , stream <nl> - if ( ( pos = uri . rfind ( " / " ) ) ! = string : : npos ) { <nl> - req - > stream = uri . substr ( pos + 1 ) ; <nl> - req - > tcUrl = uri = uri . substr ( 0 , pos ) ; <nl> + if ( srs_string_contains ( uri , " / " ) ) { <nl> + req - > stream = srs_path_basename ( uri ) ; <nl> + req - > tcUrl = uri = srs_path_dirname ( uri ) ; <nl> } <nl> <nl> srs_discovery_tc_url ( req - > tcUrl , <nl> class SrsIngestSrsContext <nl> return ret ; <nl> } <nl> <nl> - if ( ( ret = ic - > parse ( oc ) ) ! = ERROR_SUCCESS ) { <nl> + if ( ( ret = ic - > parse ( oc , oc ) ) ! = ERROR_SUCCESS ) { <nl> srs_warn ( " proxy ts to rtmp failed . ret = % d " , ret ) ; <nl> return ret ; <nl> } <nl> mmm a / trunk / src / protocol / srs_raw_avc . cpp <nl> ppp b / trunk / src / protocol / srs_raw_avc . cpp <nl> int SrsRawAacStream : : adts_demux ( SrsStream * stream , char * * pframe , int * pnb_frame <nl> * and set to ‘ 0 ’ if the audio data are MPEG - 4 . See also ISO / IEC 11172 - 3 , subclause 2 . 4 . 2 . 3 . <nl> * / <nl> if ( id ! = 0x01 ) { <nl> - ret = ERROR_ADTS_ID_NOT_AAC ; <nl> - srs_warn ( " adts : id must be 1 ( aac ) , actual 0 ( mp4a ) . ret = % d " , ret ) ; <nl> - return ret ; <nl> + srs_info ( " adts : id must be 1 ( aac ) , actual 0 ( mp4a ) . ret = % d " , ret ) ; <nl> + <nl> + / / well , some system always use 0 , but actually is aac format . <nl> + / / for example , houjian vod ts always set the aac id to 0 , actually 1 . <nl> + / / we just ignore it , and alwyas use 1 ( aac ) to demux . <nl> + id = 0x01 ; <nl> } <nl> <nl> int16_t sfiv = stream - > read_2bytes ( ) ; <nl>
support ingest hls with m3u8 in m3u8 .
ossrs/srs
a28eec89b0a530965c1ff6e9ea665f2e8d93f6ae
2015-04-21T04:53:45Z
mmm a / hphp / hack / src / typing / typing_env . ml <nl> ppp b / hphp / hack / src / typing / typing_env . ml <nl> let rec is_tvar ~ elide_nullable ty var = <nl> | ( _ , Toption ty ) when elide_nullable - > is_tvar ~ elide_nullable ty var <nl> | _ - > false <nl> <nl> + let empty_tvar_info = <nl> + { lower_bounds = empty_bounds ; <nl> + upper_bounds = empty_bounds ; <nl> + appears_covariantly = false ; <nl> + appears_contravariantly = false ; <nl> + } <nl> + <nl> + let get_tvar_info tvenv var = <nl> + Option . value ( IMap . get var tvenv ) ~ default : empty_tvar_info <nl> + <nl> ( * Add a single new upper bound [ ty ] to type variable [ var ] in [ tvenv ] * ) <nl> let add_tvenv_upper_bound_ tvenv var ty = <nl> ( * Don ' t add superfluous v < : v or v < : ? v to environment * ) <nl> if is_tvar ~ elide_nullable : true ty var <nl> then tvenv <nl> - else match IMap . get var tvenv with <nl> - | None - > <nl> - IMap . add var <nl> - { lower_bounds = empty_bounds ; upper_bounds = singleton_bound ty } tvenv <nl> - | Some { lower_bounds ; upper_bounds } - > <nl> - IMap . add var <nl> - { lower_bounds ; upper_bounds = ty + + upper_bounds } tvenv <nl> + else <nl> + let tvinfo = get_tvar_info tvenv var in <nl> + IMap . add var { tvinfo with upper_bounds = ty + + tvinfo . upper_bounds } tvenv <nl> <nl> ( * Add a single new lower bound [ ty ] to type variable [ var ] in [ tvenv ] * ) <nl> let add_tvenv_lower_bound_ tvenv var ty = <nl> let add_tvenv_lower_bound_ tvenv var ty = <nl> if is_tvar ~ elide_nullable : false ty var <nl> then tvenv <nl> else <nl> - match IMap . get var tvenv with <nl> - | None - > <nl> - IMap . add var <nl> - { lower_bounds = singleton_bound ty ; upper_bounds = empty_bounds } tvenv <nl> - | Some { lower_bounds ; upper_bounds } - > <nl> - IMap . add var <nl> - { lower_bounds = ty + + lower_bounds ; upper_bounds } tvenv <nl> + let tvinfo = get_tvar_info tvenv var in <nl> + IMap . add var { tvinfo with lower_bounds = ty + + tvinfo . lower_bounds } tvenv <nl> <nl> let env_with_tvenv env tvenv = <nl> { env with tvenv = tvenv } <nl> let env_with_tvenv env tvenv = <nl> match intersect with <nl> | None - > env_with_tvenv env ( add_tvenv_upper_bound_ tvenv var ty ) <nl> | Some intersect - > <nl> - let tyl = intersect ty ( TySet . elements ( get_tyvar_upper_bounds env var ) ) in <nl> + let tvinfo = get_tvar_info tvenv var in <nl> + let tyl = intersect ty ( TySet . elements tvinfo . upper_bounds ) in <nl> let add ty tys = <nl> if is_tvar ~ elide_nullable : true ty var <nl> then tys else TySet . add ty tys in <nl> let upper_bounds = List . fold_right ~ init : TySet . empty ~ f : add tyl in <nl> - let lower_bounds = get_tyvar_lower_bounds env var in <nl> - env_with_tvenv env ( IMap . add var { lower_bounds ; upper_bounds } tvenv ) <nl> + env_with_tvenv env ( IMap . add var { tvinfo with upper_bounds } tvenv ) <nl> <nl> ( * Add a single new upper bound [ ty ] to type variable [ var ] in [ env . tvenv ] . <nl> * If the optional [ union ] operation is supplied , then use this to avoid <nl> let add_tyvar_lower_bound ? union env var ty = <nl> match union with <nl> | None - > env_with_tvenv env ( add_tvenv_lower_bound_ tvenv var ty ) <nl> | Some union - > <nl> - let tyl = union ty ( TySet . elements ( get_tyvar_lower_bounds env var ) ) in <nl> + let tvinfo = get_tvar_info tvenv var in <nl> + let tyl = union ty ( TySet . elements tvinfo . lower_bounds ) in <nl> let lower_bounds = List . fold_right ~ init : TySet . empty ~ f : TySet . add tyl in <nl> - let upper_bounds = get_tyvar_upper_bounds env var in <nl> - env_with_tvenv env ( IMap . add var { lower_bounds ; upper_bounds } tvenv ) <nl> + env_with_tvenv env ( IMap . add var { tvinfo with lower_bounds } tvenv ) <nl> + <nl> + let set_tyvar_appears_covariantly env var = <nl> + let tvinfo = get_tvar_info env . tvenv var in <nl> + env_with_tvenv env ( IMap . add var { tvinfo with appears_covariantly = true } env . tvenv ) <nl> + <nl> + let set_tyvar_appears_contravariantly env var = <nl> + let tvinfo = get_tvar_info env . tvenv var in <nl> + env_with_tvenv env ( IMap . add var { tvinfo with appears_contravariantly = true } env . tvenv ) <nl> <nl> let rec props_to_env env remain props = <nl> match props with <nl> mmm a / hphp / hack / src / typing / typing_env . mli <nl> ppp b / hphp / hack / src / typing / typing_env . mli <nl> val add_tyvar_upper_bound : <nl> val add_tyvar_lower_bound : <nl> ? union : ( locl ty - > locl ty list - > locl ty list ) - > <nl> env - > int - > locl ty - > env <nl> - <nl> + val set_tyvar_appears_covariantly : <nl> + env - > int - > env <nl> + val set_tyvar_appears_contravariantly : <nl> + env - > int - > env <nl> val error_if_reactive_context : env - > ( unit - > unit ) - > unit <nl> val error_if_shallow_reactive_context : env - > ( unit - > unit ) - > unit <nl> val forward_compat_ge : env - > int - > bool <nl> mmm a / hphp / hack / src / typing / typing_env_types . ml <nl> ppp b / hphp / hack / src / typing / typing_env_types . ml <nl> let pp_anon _ _ = Printf . printf " % s \ n " " < anon > " <nl> let show_tfun _ = " < tfun > " <nl> let pp_tfun _ _ = Printf . printf " % s \ n " " < tfun > " <nl> <nl> + type tvar_info = { <nl> + ( * Does this type variable appear covariantly in the type of the expression ? <nl> + * ) <nl> + appears_covariantly : bool ; <nl> + ( * Does this type variable appear contravariantly in the type of the expression ? <nl> + * If it appears in an invariant position then both will be true ; if it doesn ' t <nl> + * appear at all then both will be false <nl> + * ) <nl> + appears_contravariantly : bool ; <nl> + lower_bounds : TySet . t ; <nl> + upper_bounds : TySet . t ; <nl> + } <nl> + <nl> type env = { <nl> ( * position of the function / method being checked * ) <nl> function_pos : Pos . t ; <nl> type env = { <nl> global_tpenv : tpenv ; <nl> subtype_prop : Typing_logic . subtype_prop ; <nl> log_levels : int SMap . t ; <nl> - tvenv : tparam_info IMap . t ; <nl> + tvenv : tvar_info IMap . t ; <nl> } <nl> and genv = { <nl> tcopt : TypecheckerOptions . t ; <nl> mmm a / hphp / hack / src / typing / typing_env_types_sig . mli <nl> ppp b / hphp / hack / src / typing / typing_env_types_sig . mli <nl> <nl> tpenv : tpenv ; <nl> } <nl> <nl> + type tvar_info = { <nl> + appears_covariantly : bool ; <nl> + appears_contravariantly : bool ; <nl> + lower_bounds : TySet . t ; <nl> + upper_bounds : TySet . t ; <nl> + } <nl> + <nl> type env = { <nl> ( * position of the function / method being checked * ) <nl> function_pos : Pos . t ; <nl> <nl> global_tpenv : tpenv ; <nl> subtype_prop : Typing_logic . subtype_prop ; <nl> log_levels : int SMap . t ; <nl> - tvenv : tparam_info IMap . t ; <nl> + tvenv : tvar_info IMap . t ; <nl> } <nl> and genv = { <nl> tcopt : TypecheckerOptions . t ; <nl>
Add variance information to type variable environment
facebook/hhvm
1e2e9b32918fa40b872387f61aeeabceb4c4784f
2018-11-13T18:54:49Z
mmm a / modules / core / perf / perf_dft . cpp <nl> ppp b / modules / core / perf / perf_dft . cpp <nl> using namespace perf ; <nl> using std : : tr1 : : make_tuple ; <nl> using std : : tr1 : : get ; <nl> <nl> - # define MAT_TYPES_DFT CV_32FC1 , CV_64FC1 <nl> - # define MAT_SIZES_DFT sz1080p , sz2K <nl> - # define TEST_MATS_DFT testing : : Combine ( testing : : Values ( MAT_SIZES_DFT ) , testing : : Values ( MAT_TYPES_DFT ) ) <nl> + # define MAT_TYPES_DFT CV_32FC1 , CV_32FC2 , CV_64FC1 <nl> + # define MAT_SIZES_DFT cv : : Size ( 320 , 480 ) , cv : : Size ( 800 , 600 ) , cv : : Size ( 1280 , 1024 ) , sz1080p , sz2K <nl> + CV_ENUM ( FlagsType , 0 , DFT_INVERSE , DFT_SCALE , DFT_COMPLEX_OUTPUT , DFT_ROWS , DFT_INVERSE | DFT_COMPLEX_OUTPUT ) <nl> + # define TEST_MATS_DFT testing : : Combine ( testing : : Values ( MAT_SIZES_DFT ) , testing : : Values ( MAT_TYPES_DFT ) , FlagsType : : all ( ) ) <nl> <nl> - PERF_TEST_P ( Size_MatType , dft , TEST_MATS_DFT ) <nl> + typedef std : : tr1 : : tuple < Size , MatType , FlagsType > Size_MatType_FlagsType_t ; <nl> + typedef perf : : TestBaseWithParam < Size_MatType_FlagsType_t > Size_MatType_FlagsType ; <nl> + <nl> + PERF_TEST_P ( Size_MatType_FlagsType , dft , TEST_MATS_DFT ) <nl> { <nl> Size sz = get < 0 > ( GetParam ( ) ) ; <nl> int type = get < 1 > ( GetParam ( ) ) ; <nl> + int flags = get < 2 > ( GetParam ( ) ) ; <nl> <nl> Mat src ( sz , type ) ; <nl> Mat dst ( sz , type ) ; <nl> <nl> declare . in ( src , WARMUP_RNG ) . time ( 60 ) ; <nl> <nl> - TEST_CYCLE ( ) dft ( src , dst ) ; <nl> + TEST_CYCLE ( ) dft ( src , dst , flags ) ; <nl> <nl> SANITY_CHECK ( dst , 1e - 5 , ERROR_RELATIVE ) ; <nl> - } <nl> + } <nl> \ No newline at end of file <nl> mmm a / modules / core / src / dxt . cpp <nl> ppp b / modules / core / src / dxt . cpp <nl> typedef IppStatus ( CV_STDCALL * IppDFTGetSizeFunc ) ( int , int , IppHintAlgorithm , in <nl> typedef IppStatus ( CV_STDCALL * IppDFTInitFunc ) ( int , int , IppHintAlgorithm , void * , uchar * ) ; <nl> # endif <nl> <nl> + namespace cv <nl> + { <nl> + # if defined USE_IPP_DFT & & ! defined HAVE_IPP_ICV_ONLY <nl> + <nl> + static bool ippi_DFT_C_32F ( const Mat & src , Mat & dst , bool inv , int norm_flag ) <nl> + { <nl> + IppStatus status ; <nl> + Ipp8u * pBuffer = 0 ; <nl> + Ipp8u * pMemInit = 0 ; <nl> + int sizeBuffer = 0 ; <nl> + int sizeSpec = 0 ; <nl> + int sizeInit = 0 ; <nl> + <nl> + IppiSize srcRoiSize = { src . cols , src . rows } ; <nl> + <nl> + status = ippiDFTGetSize_C_32fc ( srcRoiSize , norm_flag , ippAlgHintNone , & sizeSpec , & sizeInit , & sizeBuffer ) ; <nl> + if ( status < 0 ) <nl> + return false ; <nl> + <nl> + IppiDFTSpec_C_32fc * pDFTSpec = ( IppiDFTSpec_C_32fc * ) ippMalloc ( sizeSpec ) ; <nl> + <nl> + if ( sizeInit > 0 ) <nl> + pMemInit = ( Ipp8u * ) ippMalloc ( sizeInit ) ; <nl> + <nl> + if ( sizeBuffer > 0 ) <nl> + pBuffer = ( Ipp8u * ) ippMalloc ( sizeBuffer ) ; <nl> + <nl> + status = ippiDFTInit_C_32fc ( srcRoiSize , norm_flag , ippAlgHintNone , pDFTSpec , pMemInit ) ; <nl> + <nl> + if ( sizeInit > 0 ) <nl> + ippFree ( pMemInit ) ; <nl> + <nl> + if ( status < 0 ) <nl> + { <nl> + ippFree ( pDFTSpec ) ; <nl> + if ( sizeBuffer > 0 ) <nl> + ippFree ( pBuffer ) ; <nl> + return false ; <nl> + } <nl> + <nl> + if ( ! inv ) <nl> + status = ippiDFTFwd_CToC_32fc_C1R ( ( Ipp32fc * ) src . data , ( int ) src . step , ( Ipp32fc * ) dst . data , ( int ) dst . step , pDFTSpec , pBuffer ) ; <nl> + else <nl> + status = ippiDFTInv_CToC_32fc_C1R ( ( Ipp32fc * ) src . data , ( int ) src . step , ( Ipp32fc * ) dst . data , ( int ) dst . step , pDFTSpec , pBuffer ) ; <nl> + <nl> + if ( sizeBuffer > 0 ) <nl> + ippFree ( pBuffer ) ; <nl> + <nl> + ippFree ( pDFTSpec ) ; <nl> + <nl> + return status > = 0 ; <nl> + } <nl> + <nl> + static bool ippi_DFT_R_32F ( const Mat & src , Mat & dst , bool inv , int norm_flag ) <nl> + { <nl> + IppStatus status ; <nl> + Ipp8u * pBuffer = 0 ; <nl> + Ipp8u * pMemInit = 0 ; <nl> + int sizeBuffer = 0 ; <nl> + int sizeSpec = 0 ; <nl> + int sizeInit = 0 ; <nl> + <nl> + IppiSize srcRoiSize = { src . cols , src . rows } ; <nl> + <nl> + status = ippiDFTGetSize_R_32f ( srcRoiSize , norm_flag , ippAlgHintNone , & sizeSpec , & sizeInit , & sizeBuffer ) ; <nl> + if ( status < 0 ) <nl> + return false ; <nl> + <nl> + IppiDFTSpec_R_32f * pDFTSpec = ( IppiDFTSpec_R_32f * ) ippMalloc ( sizeSpec ) ; <nl> + <nl> + if ( sizeInit > 0 ) <nl> + pMemInit = ( Ipp8u * ) ippMalloc ( sizeInit ) ; <nl> + <nl> + if ( sizeBuffer > 0 ) <nl> + pBuffer = ( Ipp8u * ) ippMalloc ( sizeBuffer ) ; <nl> + <nl> + status = ippiDFTInit_R_32f ( srcRoiSize , norm_flag , ippAlgHintNone , pDFTSpec , pMemInit ) ; <nl> + <nl> + if ( sizeInit > 0 ) <nl> + ippFree ( pMemInit ) ; <nl> + <nl> + if ( status < 0 ) <nl> + { <nl> + ippFree ( pDFTSpec ) ; <nl> + if ( sizeBuffer > 0 ) <nl> + ippFree ( pBuffer ) ; <nl> + return false ; <nl> + } <nl> + <nl> + if ( ! inv ) <nl> + status = ippiDFTFwd_RToPack_32f_C1R ( ( float * ) src . data , ( int ) ( src . step ) , ( float * ) ( dst . data ) , ( int ) dst . step , pDFTSpec , pBuffer ) ; <nl> + else <nl> + status = ippiDFTInv_PackToR_32f_C1R ( ( float * ) src . data , ( int ) src . step , ( float * ) dst . data , ( int ) dst . step , pDFTSpec , pBuffer ) ; <nl> + <nl> + if ( sizeBuffer > 0 ) <nl> + ippFree ( pBuffer ) ; <nl> + <nl> + ippFree ( pDFTSpec ) ; <nl> + <nl> + return status > = 0 ; <nl> + } <nl> + <nl> + # endif <nl> + } <nl> + <nl> # ifdef HAVE_CLAMDFFT <nl> <nl> namespace cv { <nl> void cv : : dft ( InputArray _src0 , OutputArray _dst , int flags , int nonzero_rows ) <nl> <nl> Mat dst = _dst . getMat ( ) ; <nl> <nl> + # if defined USE_IPP_DFT & & ! defined HAVE_IPP_ICV_ONLY <nl> + <nl> + if ( ( src . depth ( ) = = CV_32F ) & & ( flags & DFT_ROWS ) = = 0 & & ( src . total ( ) > ( int ) ( 1 < < 6 ) ) ) <nl> + if ( ! real_transform ) <nl> + { <nl> + if ( ippi_DFT_C_32F ( src , dst , inv , ipp_norm_flag ) ) <nl> + return ; <nl> + setIppErrorStatus ( ) ; <nl> + } <nl> + else if ( inv | | ! ( flags & DFT_COMPLEX_OUTPUT ) ) <nl> + { <nl> + if ( ippi_DFT_R_32F ( src , dst , inv , ipp_norm_flag ) ) <nl> + return ; <nl> + setIppErrorStatus ( ) ; <nl> + } <nl> + # endif <nl> + <nl> if ( ! real_transform ) <nl> elem_size = complex_elem_size ; <nl> <nl>
IPP : CV : : dft
opencv/opencv
2d71c094b32ee948fa1f54658e7645ca7d2b07a7
2014-04-23T11:52:05Z
mmm a / src / ppc / regexp - macro - assembler - ppc . cc <nl> ppp b / src / ppc / regexp - macro - assembler - ppc . cc <nl> int RegExpMacroAssemblerPPC : : CheckStackGuardState ( Address * return_address , <nl> Address re_frame ) { <nl> return NativeRegExpMacroAssembler : : CheckStackGuardState ( <nl> frame_entry < Isolate * > ( re_frame , kIsolate ) , <nl> - frame_entry < int > ( re_frame , kStartIndex ) , <nl> - frame_entry < int > ( re_frame , kDirectCall ) = = 1 , return_address , re_code , <nl> - frame_entry_address < String * > ( re_frame , kInputString ) , <nl> + frame_entry < intptr_t > ( re_frame , kStartIndex ) , <nl> + frame_entry < intptr_t > ( re_frame , kDirectCall ) = = 1 , return_address , <nl> + re_code , frame_entry_address < String * > ( re_frame , kInputString ) , <nl> frame_entry_address < const byte * > ( re_frame , kInputStart ) , <nl> frame_entry_address < const byte * > ( re_frame , kInputEnd ) ) ; <nl> } <nl>
PPC : Always update raw pointers when handling interrupts inside RegExp code .
v8/v8
18f9771db9e514736ff8d98a3bdfa8cba08c7e4c
2015-04-10T21:54:40Z
mmm a / src / wasm / baseline / arm / liftoff - assembler - arm . h <nl> ppp b / src / wasm / baseline / arm / liftoff - assembler - arm . h <nl> void LiftoffAssembler : : LoadTransform ( LiftoffRegister dst , Register src_addr , <nl> LoadType type , <nl> LoadTransformationKind transform , <nl> uint32_t * protected_load_pc ) { <nl> - bailout ( kSimd , " Load transform unimplemented " ) ; <nl> + UseScratchRegisterScope temps ( this ) ; <nl> + Register actual_src_addr = liftoff : : CalculateActualAddress ( <nl> + this , & temps , src_addr , offset_reg , offset_imm ) ; <nl> + * protected_load_pc = pc_offset ( ) ; <nl> + <nl> + if ( transform = = LoadTransformationKind : : kExtend ) { <nl> + MachineType memtype = type . mem_type ( ) ; <nl> + if ( memtype = = MachineType : : Int8 ( ) ) { <nl> + vld1 ( Neon8 , NeonListOperand ( dst . low_fp ( ) ) , <nl> + NeonMemOperand ( actual_src_addr ) ) ; <nl> + vmovl ( NeonS8 , liftoff : : GetSimd128Register ( dst ) , dst . low_fp ( ) ) ; <nl> + } else if ( memtype = = MachineType : : Uint8 ( ) ) { <nl> + vld1 ( Neon8 , NeonListOperand ( dst . low_fp ( ) ) , <nl> + NeonMemOperand ( actual_src_addr ) ) ; <nl> + vmovl ( NeonU8 , liftoff : : GetSimd128Register ( dst ) , dst . low_fp ( ) ) ; <nl> + } else if ( memtype = = MachineType : : Int16 ( ) ) { <nl> + vld1 ( Neon16 , NeonListOperand ( dst . low_fp ( ) ) , <nl> + NeonMemOperand ( actual_src_addr ) ) ; <nl> + vmovl ( NeonS16 , liftoff : : GetSimd128Register ( dst ) , dst . low_fp ( ) ) ; <nl> + } else if ( memtype = = MachineType : : Uint16 ( ) ) { <nl> + vld1 ( Neon16 , NeonListOperand ( dst . low_fp ( ) ) , <nl> + NeonMemOperand ( actual_src_addr ) ) ; <nl> + vmovl ( NeonU16 , liftoff : : GetSimd128Register ( dst ) , dst . low_fp ( ) ) ; <nl> + } else if ( memtype = = MachineType : : Int32 ( ) ) { <nl> + vld1 ( Neon32 , NeonListOperand ( dst . low_fp ( ) ) , <nl> + NeonMemOperand ( actual_src_addr ) ) ; <nl> + vmovl ( NeonS32 , liftoff : : GetSimd128Register ( dst ) , dst . low_fp ( ) ) ; <nl> + } else if ( memtype = = MachineType : : Uint32 ( ) ) { <nl> + vld1 ( Neon32 , NeonListOperand ( dst . low_fp ( ) ) , <nl> + NeonMemOperand ( actual_src_addr ) ) ; <nl> + vmovl ( NeonU32 , liftoff : : GetSimd128Register ( dst ) , dst . low_fp ( ) ) ; <nl> + } <nl> + } else { <nl> + DCHECK_EQ ( LoadTransformationKind : : kSplat , transform ) ; <nl> + bailout ( kSimd , " load splats unimplemented " ) ; <nl> + } <nl> } <nl> <nl> void LiftoffAssembler : : emit_f64x2_splat ( LiftoffRegister dst , <nl> mmm a / src / wasm / baseline / arm64 / liftoff - assembler - arm64 . h <nl> ppp b / src / wasm / baseline / arm64 / liftoff - assembler - arm64 . h <nl> void LiftoffAssembler : : LoadTransform ( LiftoffRegister dst , Register src_addr , <nl> LoadType type , <nl> LoadTransformationKind transform , <nl> uint32_t * protected_load_pc ) { <nl> - bailout ( kSimd , " Load transform unimplemented " ) ; <nl> + UseScratchRegisterScope temps ( this ) ; <nl> + MemOperand src_op = <nl> + liftoff : : GetMemOp ( this , & temps , src_addr , offset_reg , offset_imm ) ; <nl> + * protected_load_pc = pc_offset ( ) ; <nl> + <nl> + if ( transform = = LoadTransformationKind : : kExtend ) { <nl> + MachineType memtype = type . mem_type ( ) ; <nl> + if ( memtype = = MachineType : : Int8 ( ) ) { <nl> + Ldr ( dst . fp ( ) . D ( ) , src_op ) ; <nl> + Sxtl ( dst . fp ( ) . V8H ( ) , dst . fp ( ) . V8B ( ) ) ; <nl> + } else if ( memtype = = MachineType : : Uint8 ( ) ) { <nl> + Ldr ( dst . fp ( ) . D ( ) , src_op ) ; <nl> + Uxtl ( dst . fp ( ) . V8H ( ) , dst . fp ( ) . V8B ( ) ) ; <nl> + } else if ( memtype = = MachineType : : Int16 ( ) ) { <nl> + Ldr ( dst . fp ( ) . D ( ) , src_op ) ; <nl> + Sxtl ( dst . fp ( ) . V4S ( ) , dst . fp ( ) . V4H ( ) ) ; <nl> + } else if ( memtype = = MachineType : : Uint16 ( ) ) { <nl> + Ldr ( dst . fp ( ) . D ( ) , src_op ) ; <nl> + Uxtl ( dst . fp ( ) . V4S ( ) , dst . fp ( ) . V4H ( ) ) ; <nl> + } else if ( memtype = = MachineType : : Int32 ( ) ) { <nl> + Ldr ( dst . fp ( ) . D ( ) , src_op ) ; <nl> + Sxtl ( dst . fp ( ) . V2D ( ) , dst . fp ( ) . V2S ( ) ) ; <nl> + } else if ( memtype = = MachineType : : Uint32 ( ) ) { <nl> + Ldr ( dst . fp ( ) . D ( ) , src_op ) ; <nl> + Uxtl ( dst . fp ( ) . V2D ( ) , dst . fp ( ) . V2S ( ) ) ; <nl> + } <nl> + } else { <nl> + DCHECK_EQ ( LoadTransformationKind : : kSplat , transform ) ; <nl> + bailout ( kSimd , " load splats unimplemented " ) ; <nl> + } <nl> } <nl> <nl> void LiftoffAssembler : : emit_f64x2_splat ( LiftoffRegister dst , <nl>
[ wasm - simd ] [ liftoff ] [ arm ] [ arm64 ] Implement load extends
v8/v8
a0d493e27e8bb3c643fbedc388350766e9f1f874
2020-05-20T19:02:24Z
mmm a / lib / browser / api / auto - updater / auto - updater - win . js <nl> ppp b / lib / browser / api / auto - updater / auto - updater - win . js <nl> <nl> ' use strict ' <nl> <nl> - const app = require ( ' electron ' ) . app <nl> - const EventEmitter = require ( ' events ' ) . EventEmitter <nl> + const { app } = require ( ' electron ' ) <nl> + const { EventEmitter } = require ( ' events ' ) <nl> const squirrelUpdate = require ( ' . / squirrel - update - win ' ) <nl> - const util = require ( ' util ' ) <nl> <nl> - function AutoUpdater ( ) { <nl> - EventEmitter . call ( this ) <nl> - } <nl> - <nl> - util . inherits ( AutoUpdater , EventEmitter ) <nl> - <nl> - AutoUpdater . prototype . quitAndInstall = function ( ) { <nl> - if ( ! this . updateAvailable ) { <nl> - return this . emitError ( ' No update available , can \ ' t quit and install ' ) <nl> + class AutoUpdater extends EventEmitter { <nl> + quitAndInstall ( ) { <nl> + if ( ! this . updateAvailable ) { <nl> + return this . emitError ( ' No update available , can \ ' t quit and install ' ) <nl> + } <nl> + squirrelUpdate . processStart ( ) <nl> + return app . quit ( ) <nl> } <nl> - squirrelUpdate . processStart ( ) <nl> - return app . quit ( ) <nl> - } <nl> - <nl> - AutoUpdater . prototype . getFeedURL = function ( ) { <nl> - return this . updateURL <nl> - } <nl> <nl> - AutoUpdater . prototype . setFeedURL = function ( updateURL , headers ) { <nl> - this . updateURL = updateURL <nl> - } <nl> - <nl> - AutoUpdater . prototype . checkForUpdates = function ( ) { <nl> - if ( ! this . updateURL ) { <nl> - return this . emitError ( ' Update URL is not set ' ) <nl> + getFeedURL ( ) { <nl> + return this . updateURL <nl> } <nl> - if ( ! squirrelUpdate . supported ( ) ) { <nl> - return this . emitError ( ' Can not find Squirrel ' ) <nl> + <nl> + setFeedURL ( updateURL , headers ) { <nl> + this . updateURL = updateURL <nl> } <nl> - this . emit ( ' checking - for - update ' ) <nl> - squirrelUpdate . download ( this . updateURL , ( error , update ) = > { <nl> - if ( error ! = null ) { <nl> - return this . emitError ( error ) <nl> + <nl> + checkForUpdates ( ) { <nl> + if ( ! this . updateURL ) { <nl> + return this . emitError ( ' Update URL is not set ' ) <nl> } <nl> - if ( update = = null ) { <nl> - this . updateAvailable = false <nl> - return this . emit ( ' update - not - available ' ) <nl> + if ( ! squirrelUpdate . supported ( ) ) { <nl> + return this . emitError ( ' Can not find Squirrel ' ) <nl> } <nl> - this . updateAvailable = true <nl> - this . emit ( ' update - available ' ) <nl> - squirrelUpdate . update ( this . updateURL , ( error ) = > { <nl> - var date , releaseNotes , version <nl> + this . emit ( ' checking - for - update ' ) <nl> + squirrelUpdate . download ( this . updateURL , ( error , update ) = > { <nl> if ( error ! = null ) { <nl> return this . emitError ( error ) <nl> } <nl> - releaseNotes = update . releaseNotes <nl> - version = update . version <nl> + if ( update = = null ) { <nl> + this . updateAvailable = false <nl> + return this . emit ( ' update - not - available ' ) <nl> + } <nl> + this . updateAvailable = true <nl> + this . emit ( ' update - available ' ) <nl> + squirrelUpdate . update ( this . updateURL , ( error ) = > { <nl> + var date , releaseNotes , version <nl> + if ( error ! = null ) { <nl> + return this . emitError ( error ) <nl> + } <nl> + releaseNotes = update . releaseNotes <nl> + version = update . version <nl> <nl> - / / Following information is not available on Windows , so fake them . <nl> - date = new Date ( ) <nl> - this . emit ( ' update - downloaded ' , { } , releaseNotes , version , date , this . updateURL , ( ) = > { <nl> - this . quitAndInstall ( ) <nl> + / / Following information is not available on Windows , so fake them . <nl> + date = new Date ( ) <nl> + this . emit ( ' update - downloaded ' , { } , releaseNotes , version , date , this . updateURL , ( ) = > { <nl> + this . quitAndInstall ( ) <nl> + } ) <nl> } ) <nl> } ) <nl> - } ) <nl> - } <nl> + } <nl> <nl> - / / Private : Emit both error object and message , this is to keep compatibility <nl> - / / with Old APIs . <nl> - AutoUpdater . prototype . emitError = function ( message ) { <nl> - return this . emit ( ' error ' , new Error ( message ) , message ) <nl> + / / Private : Emit both error object and message , this is to keep compatibility <nl> + / / with Old APIs . <nl> + emitError ( message ) { <nl> + return this . emit ( ' error ' , new Error ( message ) , message ) <nl> + } <nl> } <nl> <nl> module . exports = new AutoUpdater ( ) <nl>
Merge pull request from electron / win - autoupdater - es6
electron/electron
8d941a655994681f9d3328a6608bd96e5236e64f
2016-07-26T03:46:00Z
mmm a / src / userspace / console_user_server / Makefile <nl> ppp b / src / userspace / console_user_server / Makefile <nl> clean : <nl> rm - f * . xcodeproj / * . pbxuser <nl> rm - rf * . xcodeproj / xcuserdata <nl> rm - rf * . xcodeproj / project . xcworkspace / xcuserdata <nl> - rm - f * . app . zip <nl> <nl> xcode : <nl> open * . xcodeproj <nl> <nl> run : <nl> - . / build / Release / console_user_server <nl> + . / build / Release / karabiner_console_user_server <nl> deleted file mode 100644 <nl> index 83eca7647 . . 000000000 <nl> mmm a / src / userspace / console_user_server / console_user_server . xcodeproj / project . xcworkspace / contents . xcworkspacedata <nl> ppp / dev / null <nl> <nl> - < ? xml version = " 1 . 0 " encoding = " UTF - 8 " ? > <nl> - < Workspace <nl> - version = " 1 . 0 " > <nl> - < FileRef <nl> - location = " self : console_user_server . xcodeproj " > <nl> - < / FileRef > <nl> - < / Workspace > <nl> similarity index 93 % <nl> rename from src / userspace / console_user_server / console_user_server . xcodeproj / project . pbxproj <nl> rename to src / userspace / console_user_server / karabiner_console_user_server . xcodeproj / project . pbxproj <nl> mmm a / src / userspace / console_user_server / console_user_server . xcodeproj / project . pbxproj <nl> ppp b / src / userspace / console_user_server / karabiner_console_user_server . xcodeproj / project . pbxproj <nl> <nl> 341F59D71D538C4000B441A8 / * userspace_defs . h * / = { isa = PBXFileReference ; fileEncoding = 4 ; lastKnownFileType = sourcecode . c . h ; name = userspace_defs . h ; path = . . / . . / share / userspace_defs . h ; sourceTree = " < group > " ; } ; <nl> 341F59DA1D54EABD00B441A8 / * iokit_user_client . hpp * / = { isa = PBXFileReference ; fileEncoding = 4 ; lastKnownFileType = sourcecode . cpp . h ; name = iokit_user_client . hpp ; path = . . / . . / share / iokit_user_client . hpp ; sourceTree = " < group > " ; } ; <nl> 341F59DB1D57789500B441A8 / * iokit_utility . hpp * / = { isa = PBXFileReference ; fileEncoding = 4 ; lastKnownFileType = sourcecode . cpp . h ; name = iokit_utility . hpp ; path = . . / . . / share / iokit_utility . hpp ; sourceTree = " < group > " ; } ; <nl> - 344149111D212A1600C8ECFC / * console_user_server * / = { isa = PBXFileReference ; explicitFileType = " compiled . mach - o . executable " ; includeInIndex = 0 ; path = console_user_server ; sourceTree = BUILT_PRODUCTS_DIR ; } ; <nl> + 344149111D212A1600C8ECFC / * karabiner_console_user_server * / = { isa = PBXFileReference ; explicitFileType = " compiled . mach - o . executable " ; includeInIndex = 0 ; path = karabiner_console_user_server ; sourceTree = BUILT_PRODUCTS_DIR ; } ; <nl> 344149141D212A1600C8ECFC / * main . cpp * / = { isa = PBXFileReference ; lastKnownFileType = sourcecode . cpp . cpp ; path = main . cpp ; sourceTree = " < group > " ; } ; <nl> 3446AA901D49A63E00337B36 / * io_hid_post_event_wrapper . hpp * / = { isa = PBXFileReference ; fileEncoding = 4 ; lastKnownFileType = sourcecode . cpp . h ; name = io_hid_post_event_wrapper . hpp ; path = include / io_hid_post_event_wrapper . hpp ; sourceTree = " < group > " ; } ; <nl> 345ABFFE1D60AD6D009D1FB4 / * system_preferences . hpp * / = { isa = PBXFileReference ; fileEncoding = 4 ; lastKnownFileType = sourcecode . cpp . h ; name = system_preferences . hpp ; path = . . / . . / share / system_preferences . hpp ; sourceTree = " < group > " ; } ; <nl> <nl> 344149121D212A1600C8ECFC / * Products * / = { <nl> isa = PBXGroup ; <nl> children = ( <nl> - 344149111D212A1600C8ECFC / * console_user_server * / , <nl> + 344149111D212A1600C8ECFC / * karabiner_console_user_server * / , <nl> ) ; <nl> name = Products ; <nl> sourceTree = " < group > " ; <nl> <nl> / * End PBXGroup section * / <nl> <nl> / * Begin PBXNativeTarget section * / <nl> - 344149101D212A1600C8ECFC / * console_user_server * / = { <nl> + 344149101D212A1600C8ECFC / * karabiner_console_user_server * / = { <nl> isa = PBXNativeTarget ; <nl> - buildConfigurationList = 344149181D212A1600C8ECFC / * Build configuration list for PBXNativeTarget " console_user_server " * / ; <nl> + buildConfigurationList = 344149181D212A1600C8ECFC / * Build configuration list for PBXNativeTarget " karabiner_console_user_server " * / ; <nl> buildPhases = ( <nl> 3441490D1D212A1600C8ECFC / * Sources * / , <nl> 3441490E1D212A1600C8ECFC / * Frameworks * / , <nl> <nl> ) ; <nl> dependencies = ( <nl> ) ; <nl> - name = console_user_server ; <nl> + name = karabiner_console_user_server ; <nl> productName = console_user_server ; <nl> - productReference = 344149111D212A1600C8ECFC / * console_user_server * / ; <nl> + productReference = 344149111D212A1600C8ECFC / * karabiner_console_user_server * / ; <nl> productType = " com . apple . product - type . tool " ; <nl> } ; <nl> / * End PBXNativeTarget section * / <nl> <nl> } ; <nl> } ; <nl> } ; <nl> - buildConfigurationList = 3441490C1D212A1600C8ECFC / * Build configuration list for PBXProject " console_user_server " * / ; <nl> + buildConfigurationList = 3441490C1D212A1600C8ECFC / * Build configuration list for PBXProject " karabiner_console_user_server " * / ; <nl> compatibilityVersion = " Xcode 6 . 3 " ; <nl> developmentRegion = English ; <nl> hasScannedForEncodings = 0 ; <nl> <nl> projectDirPath = " " ; <nl> projectRoot = " " ; <nl> targets = ( <nl> - 344149101D212A1600C8ECFC / * console_user_server * / , <nl> + 344149101D212A1600C8ECFC / * karabiner_console_user_server * / , <nl> ) ; <nl> } ; <nl> / * End PBXProject section * / <nl> <nl> 3441491A1D212A1600C8ECFC / * Release * / = { <nl> isa = XCBuildConfiguration ; <nl> buildSettings = { <nl> - PRODUCT_NAME = " $ ( TARGET_NAME ) " ; <nl> + PRODUCT_NAME = karabiner_console_user_server ; <nl> } ; <nl> name = Release ; <nl> } ; <nl> / * End XCBuildConfiguration section * / <nl> <nl> / * Begin XCConfigurationList section * / <nl> - 3441490C1D212A1600C8ECFC / * Build configuration list for PBXProject " console_user_server " * / = { <nl> + 3441490C1D212A1600C8ECFC / * Build configuration list for PBXProject " karabiner_console_user_server " * / = { <nl> isa = XCConfigurationList ; <nl> buildConfigurations = ( <nl> 344149171D212A1600C8ECFC / * Release * / , <nl> <nl> defaultConfigurationIsVisible = 0 ; <nl> defaultConfigurationName = Release ; <nl> } ; <nl> - 344149181D212A1600C8ECFC / * Build configuration list for PBXNativeTarget " console_user_server " * / = { <nl> + 344149181D212A1600C8ECFC / * Build configuration list for PBXNativeTarget " karabiner_console_user_server " * / = { <nl> isa = XCConfigurationList ; <nl> buildConfigurations = ( <nl> 3441491A1D212A1600C8ECFC / * Release * / , <nl> new file mode 100644 <nl> index 000000000 . . 846b53f91 <nl> mmm / dev / null <nl> ppp b / src / userspace / console_user_server / karabiner_console_user_server . xcodeproj / project . xcworkspace / contents . xcworkspacedata <nl> <nl> + < ? xml version = " 1 . 0 " encoding = " UTF - 8 " ? > <nl> + < Workspace <nl> + version = " 1 . 0 " > <nl> + < FileRef <nl> + location = " self : / Users / tekezo / repo / Karabiner - Elements / src / userspace / console_user_server / karabiner_console_user_server . xcodeproj " > <nl> + < / FileRef > <nl> + < / Workspace > <nl>
console_user_server - > karabiner_console_user_server
pqrs-org/Karabiner-Elements
8b06e11fffb72e4dccd37b6f19a113c83953a4a0
2016-08-20T09:28:08Z
mmm a / src / arm / codegen - arm . cc <nl> ppp b / src / arm / codegen - arm . cc <nl> void CodeGenerator : : GenerateStringAdd ( ZoneList < Expression * > * args ) { <nl> Load ( args - > at ( 0 ) ) ; <nl> Load ( args - > at ( 1 ) ) ; <nl> <nl> - frame_ - > CallRuntime ( Runtime : : kStringAdd , 2 ) ; <nl> + StringAddStub stub ( NO_STRING_ADD_FLAGS ) ; <nl> + frame_ - > CallStub ( & stub , 2 ) ; <nl> frame_ - > EmitPush ( r0 ) ; <nl> } <nl> <nl> static void HandleBinaryOpSlowCases ( MacroAssembler * masm , <nl> / / r1 : first argument <nl> / / r0 : second argument <nl> / / sp [ 0 ] : second argument <nl> - / / sp [ 1 ] : first argument <nl> + / / sp [ 4 ] : first argument <nl> <nl> Label not_strings , not_string1 , string1 ; <nl> __ tst ( r1 , Operand ( kSmiTagMask ) ) ; <nl> static void HandleBinaryOpSlowCases ( MacroAssembler * masm , <nl> __ b ( ge , & string1 ) ; <nl> <nl> / / First and second argument are strings . <nl> - __ TailCallRuntime ( ExternalReference ( Runtime : : kStringAdd ) , 2 , 1 ) ; <nl> + StringAddStub stub ( NO_STRING_CHECK_IN_STUB ) ; <nl> + __ TailCallStub ( & stub ) ; <nl> <nl> / / Only first argument is a string . <nl> __ bind ( & string1 ) ; <nl> static void HandleBinaryOpSlowCases ( MacroAssembler * masm , <nl> __ b ( ge , & not_strings ) ; <nl> <nl> / / Only second argument is a string . <nl> - __ b ( & not_strings ) ; <nl> __ InvokeBuiltin ( Builtins : : STRING_ADD_RIGHT , JUMP_JS ) ; <nl> <nl> __ bind ( & not_strings ) ; <nl> void StringStubBase : : GenerateCopyCharacters ( MacroAssembler * masm , <nl> __ b ( eq , & done ) ; <nl> <nl> __ bind ( & loop ) ; <nl> + __ ldrb ( scratch , MemOperand ( src , 1 , PostIndex ) ) ; <nl> + / / Perform sub between load and dependent store to get the load time to <nl> + / / complete . <nl> __ sub ( count , count , Operand ( 1 ) , SetCC ) ; <nl> - __ ldrb ( scratch , MemOperand ( src , count ) , pl ) ; <nl> - / / Move branch between load and dependent store to not waste the cycle for <nl> - / / each iteration of the loop . It does cost an extra instruction on the <nl> + __ strb ( scratch , MemOperand ( dest , 1 , PostIndex ) ) ; <nl> / / last iteration . <nl> - __ b ( mi , & done ) ; <nl> - __ strb ( scratch , MemOperand ( dest , count ) ) ; <nl> - __ b ( & loop ) ; <nl> + __ b ( gt , & loop ) ; <nl> + <nl> __ bind ( & done ) ; <nl> } <nl> <nl> void StringCompareStub : : Generate ( MacroAssembler * masm ) { <nl> Label runtime ; <nl> <nl> / / Stack frame on entry . <nl> - / / sp [ 0 ] : return address <nl> - / / sp [ 4 ] : right string <nl> - / / sp [ 8 ] : left string <nl> - <nl> - __ ldr ( r0 , MemOperand ( sp , 2 * kPointerSize ) ) ; / / left <nl> - __ ldr ( r1 , MemOperand ( sp , 1 * kPointerSize ) ) ; / / right <nl> + / / sp [ 0 ] : right string <nl> + / / sp [ 4 ] : left string <nl> + __ ldr ( r0 , MemOperand ( sp , 1 * kPointerSize ) ) ; / / left <nl> + __ ldr ( r1 , MemOperand ( sp , 0 * kPointerSize ) ) ; / / right <nl> <nl> Label not_same ; <nl> __ cmp ( r0 , r1 ) ; <nl> void StringCompareStub : : Generate ( MacroAssembler * masm ) { <nl> } <nl> <nl> <nl> + void StringAddStub : : Generate ( MacroAssembler * masm ) { <nl> + Label string_add_runtime ; <nl> + / / Stack on entry : <nl> + / / sp [ 0 ] : second argument . <nl> + / / sp [ 4 ] : first argument . <nl> + <nl> + / / Load the two arguments . <nl> + __ ldr ( r0 , MemOperand ( sp , 1 * kPointerSize ) ) ; / / First argument . <nl> + __ ldr ( r1 , MemOperand ( sp , 0 * kPointerSize ) ) ; / / Second argument . <nl> + <nl> + / / Make sure that both arguments are strings if not known in advance . <nl> + if ( string_check_ ) { <nl> + ASSERT_EQ ( 0 , kSmiTag ) ; <nl> + __ JumpIfEitherSmi ( r0 , r1 , & string_add_runtime ) ; <nl> + / / Load instance types . <nl> + __ ldr ( r4 , FieldMemOperand ( r0 , HeapObject : : kMapOffset ) ) ; <nl> + __ ldr ( r5 , FieldMemOperand ( r1 , HeapObject : : kMapOffset ) ) ; <nl> + __ ldrb ( r4 , FieldMemOperand ( r4 , Map : : kInstanceTypeOffset ) ) ; <nl> + __ ldrb ( r5 , FieldMemOperand ( r5 , Map : : kInstanceTypeOffset ) ) ; <nl> + ASSERT_EQ ( 0 , kStringTag ) ; <nl> + / / If either is not a string , go to runtime . <nl> + __ tst ( r4 , Operand ( kIsNotStringMask ) ) ; <nl> + __ tst ( r5 , Operand ( kIsNotStringMask ) , eq ) ; <nl> + __ b ( ne , & string_add_runtime ) ; <nl> + } <nl> + <nl> + / / Both arguments are strings . <nl> + / / r0 : first string <nl> + / / r1 : second string <nl> + / / r4 : first string instance type ( if string_check_ ) <nl> + / / r5 : second string instance type ( if string_check_ ) <nl> + { <nl> + Label strings_not_empty ; <nl> + / / Check if either of the strings are empty . In that case return the other . <nl> + __ ldr ( r2 , FieldMemOperand ( r0 , String : : kLengthOffset ) ) ; <nl> + __ ldr ( r3 , FieldMemOperand ( r1 , String : : kLengthOffset ) ) ; <nl> + __ cmp ( r2 , Operand ( 0 ) ) ; / / Test if first string is empty . <nl> + __ mov ( r0 , Operand ( r1 ) , LeaveCC , eq ) ; / / If first is empty , return second . <nl> + __ cmp ( r3 , Operand ( 0 ) , ne ) ; / / Else test if second string is empty . <nl> + __ b ( ne , & strings_not_empty ) ; / / If either string was empty , return r0 . <nl> + <nl> + __ IncrementCounter ( & Counters : : string_add_native , 1 , r2 , r3 ) ; <nl> + __ add ( sp , sp , Operand ( 2 * kPointerSize ) ) ; <nl> + __ Ret ( ) ; <nl> + <nl> + __ bind ( & strings_not_empty ) ; <nl> + } <nl> + <nl> + / / Both strings are non - empty . <nl> + / / r0 : first string <nl> + / / r1 : second string <nl> + / / r2 : length of first string <nl> + / / r3 : length of second string <nl> + / / r4 : first string instance type ( if string_check_ ) <nl> + / / r5 : second string instance type ( if string_check_ ) <nl> + / / Look at the length of the result of adding the two strings . <nl> + Label string_add_flat_result ; <nl> + / / Adding two lengths can ' t overflow . <nl> + ASSERT ( String : : kMaxLength * 2 > String : : kMaxLength ) ; <nl> + __ add ( r6 , r2 , Operand ( r3 ) ) ; <nl> + / / Use the runtime system when adding two one character strings , as it <nl> + / / contains optimizations for this specific case using the symbol table . <nl> + __ cmp ( r6 , Operand ( 2 ) ) ; <nl> + __ b ( eq , & string_add_runtime ) ; <nl> + / / Check if resulting string will be flat . <nl> + __ cmp ( r6 , Operand ( String : : kMinNonFlatLength ) ) ; <nl> + __ b ( lt , & string_add_flat_result ) ; <nl> + / / Handle exceptionally long strings in the runtime system . <nl> + ASSERT ( ( String : : kMaxLength & 0x80000000 ) = = 0 ) ; <nl> + ASSERT ( IsPowerOf2 ( String : : kMaxLength + 1 ) ) ; <nl> + / / kMaxLength + 1 is representable as shifted literal , kMaxLength is not . <nl> + __ cmp ( r6 , Operand ( String : : kMaxLength + 1 ) ) ; <nl> + __ b ( hs , & string_add_runtime ) ; <nl> + <nl> + / / If result is not supposed to be flat , allocate a cons string object . <nl> + / / If both strings are ascii the result is an ascii cons string . <nl> + if ( ! string_check_ ) { <nl> + __ ldr ( r4 , FieldMemOperand ( r0 , HeapObject : : kMapOffset ) ) ; <nl> + __ ldr ( r5 , FieldMemOperand ( r1 , HeapObject : : kMapOffset ) ) ; <nl> + __ ldrb ( r4 , FieldMemOperand ( r4 , Map : : kInstanceTypeOffset ) ) ; <nl> + __ ldrb ( r5 , FieldMemOperand ( r5 , Map : : kInstanceTypeOffset ) ) ; <nl> + } <nl> + Label non_ascii , allocated ; <nl> + ASSERT_EQ ( 0 , kTwoByteStringTag ) ; <nl> + __ tst ( r4 , Operand ( kStringEncodingMask ) ) ; <nl> + __ tst ( r5 , Operand ( kStringEncodingMask ) , ne ) ; <nl> + __ b ( eq , & non_ascii ) ; <nl> + <nl> + / / Allocate an ASCII cons string . <nl> + __ AllocateAsciiConsString ( r7 , r6 , r4 , r5 , & string_add_runtime ) ; <nl> + __ bind ( & allocated ) ; <nl> + / / Fill the fields of the cons string . <nl> + __ str ( r0 , FieldMemOperand ( r7 , ConsString : : kFirstOffset ) ) ; <nl> + __ str ( r1 , FieldMemOperand ( r7 , ConsString : : kSecondOffset ) ) ; <nl> + __ mov ( r0 , Operand ( r7 ) ) ; <nl> + __ IncrementCounter ( & Counters : : string_add_native , 1 , r2 , r3 ) ; <nl> + __ add ( sp , sp , Operand ( 2 * kPointerSize ) ) ; <nl> + __ Ret ( ) ; <nl> + <nl> + __ bind ( & non_ascii ) ; <nl> + / / Allocate a two byte cons string . <nl> + __ AllocateTwoByteConsString ( r7 , r6 , r4 , r5 , & string_add_runtime ) ; <nl> + __ jmp ( & allocated ) ; <nl> + <nl> + / / Handle creating a flat result . First check that both strings are <nl> + / / sequential and that they have the same encoding . <nl> + / / r0 : first string <nl> + / / r1 : second string <nl> + / / r2 : length of first string <nl> + / / r3 : length of second string <nl> + / / r4 : first string instance type ( if string_check_ ) <nl> + / / r5 : second string instance type ( if string_check_ ) <nl> + / / r6 : sum of lengths . <nl> + __ bind ( & string_add_flat_result ) ; <nl> + if ( ! string_check_ ) { <nl> + __ ldr ( r4 , FieldMemOperand ( r0 , HeapObject : : kMapOffset ) ) ; <nl> + __ ldr ( r5 , FieldMemOperand ( r1 , HeapObject : : kMapOffset ) ) ; <nl> + __ ldrb ( r4 , FieldMemOperand ( r4 , Map : : kInstanceTypeOffset ) ) ; <nl> + __ ldrb ( r5 , FieldMemOperand ( r5 , Map : : kInstanceTypeOffset ) ) ; <nl> + } <nl> + / / Check that both strings are sequential . <nl> + ASSERT_EQ ( 0 , kSeqStringTag ) ; <nl> + __ tst ( r4 , Operand ( kStringRepresentationMask ) ) ; <nl> + __ tst ( r5 , Operand ( kStringRepresentationMask ) , eq ) ; <nl> + __ b ( ne , & string_add_runtime ) ; <nl> + / / Now check if both strings have the same encoding ( ASCII / Two - byte ) . <nl> + / / r0 : first string . <nl> + / / r1 : second string . <nl> + / / r2 : length of first string . <nl> + / / r3 : length of second string . <nl> + / / r6 : sum of lengths . . <nl> + Label non_ascii_string_add_flat_result ; <nl> + ASSERT ( IsPowerOf2 ( kStringEncodingMask ) ) ; / / Just one bit to test . <nl> + __ eor ( r7 , r4 , Operand ( r5 ) ) ; <nl> + __ tst ( r7 , Operand ( kStringEncodingMask ) ) ; <nl> + __ b ( ne , & string_add_runtime ) ; <nl> + / / And see if it ' s ASCII or two - byte . <nl> + __ tst ( r4 , Operand ( kStringEncodingMask ) ) ; <nl> + __ b ( eq , & non_ascii_string_add_flat_result ) ; <nl> + <nl> + / / Both strings are sequential ASCII strings . We also know that they are <nl> + / / short ( since the sum of the lengths is less than kMinNonFlatLength ) . <nl> + __ AllocateAsciiString ( r7 , r6 , r4 , r5 , r9 , & string_add_runtime ) ; <nl> + / / Locate first character of result . <nl> + __ add ( r6 , r7 , Operand ( SeqAsciiString : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + / / Locate first character of first argument . <nl> + __ add ( r0 , r0 , Operand ( SeqAsciiString : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + / / r0 : first character of first string . <nl> + / / r1 : second string . <nl> + / / r2 : length of first string . <nl> + / / r3 : length of second string . <nl> + / / r6 : first character of result . <nl> + / / r7 : result string . <nl> + GenerateCopyCharacters ( masm , r6 , r0 , r2 , r4 , true ) ; <nl> + <nl> + / / Load second argument and locate first character . <nl> + __ add ( r1 , r1 , Operand ( SeqAsciiString : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + / / r1 : first character of second string . <nl> + / / r3 : length of second string . <nl> + / / r6 : next character of result . <nl> + / / r7 : result string . <nl> + GenerateCopyCharacters ( masm , r6 , r1 , r3 , r4 , true ) ; <nl> + __ mov ( r0 , Operand ( r7 ) ) ; <nl> + __ IncrementCounter ( & Counters : : string_add_native , 1 , r2 , r3 ) ; <nl> + __ add ( sp , sp , Operand ( 2 * kPointerSize ) ) ; <nl> + __ Ret ( ) ; <nl> + <nl> + __ bind ( & non_ascii_string_add_flat_result ) ; <nl> + / / Both strings are sequential two byte strings . <nl> + / / r0 : first string . <nl> + / / r1 : second string . <nl> + / / r2 : length of first string . <nl> + / / r3 : length of second string . <nl> + / / r6 : sum of length of strings . <nl> + __ AllocateTwoByteString ( r7 , r6 , r4 , r5 , r9 , & string_add_runtime ) ; <nl> + / / r0 : first string . <nl> + / / r1 : second string . <nl> + / / r2 : length of first string . <nl> + / / r3 : length of second string . <nl> + / / r7 : result string . <nl> + <nl> + / / Locate first character of result . <nl> + __ add ( r6 , r7 , Operand ( SeqTwoByteString : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + / / Locate first character of first argument . <nl> + __ add ( r0 , r0 , Operand ( SeqTwoByteString : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + <nl> + / / r0 : first character of first string . <nl> + / / r1 : second string . <nl> + / / r2 : length of first string . <nl> + / / r3 : length of second string . <nl> + / / r6 : first character of result . <nl> + / / r7 : result string . <nl> + GenerateCopyCharacters ( masm , r6 , r0 , r2 , r4 , false ) ; <nl> + <nl> + / / Locate first character of second argument . <nl> + __ add ( r1 , r1 , Operand ( SeqTwoByteString : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + <nl> + / / r1 : first character of second string . <nl> + / / r3 : length of second string . <nl> + / / r6 : next character of result ( after copy of first string ) . <nl> + / / r7 : result string . <nl> + GenerateCopyCharacters ( masm , r6 , r1 , r3 , r4 , false ) ; <nl> + <nl> + __ mov ( r0 , Operand ( r7 ) ) ; <nl> + __ IncrementCounter ( & Counters : : string_add_native , 1 , r2 , r3 ) ; <nl> + __ add ( sp , sp , Operand ( 2 * kPointerSize ) ) ; <nl> + __ Ret ( ) ; <nl> + <nl> + / / Just jump to runtime to add the two strings . <nl> + __ bind ( & string_add_runtime ) ; <nl> + __ TailCallRuntime ( ExternalReference ( Runtime : : kStringAdd ) , 2 , 1 ) ; <nl> + } <nl> + <nl> + <nl> # undef __ <nl> <nl> } } / / namespace v8 : : internal <nl> mmm a / src / arm / codegen - arm . h <nl> ppp b / src / arm / codegen - arm . h <nl> class StringStubBase : public CodeStub { <nl> / / be used in places where the number of characters is small and the <nl> / / additional setup and checking in GenerateCopyCharactersLong adds too much <nl> / / overhead . Copying of overlapping regions is not supported . <nl> + / / Dest register ends at the position after the last character written . <nl> void GenerateCopyCharacters ( MacroAssembler * masm , <nl> Register dest , <nl> Register src , <nl> class StringStubBase : public CodeStub { <nl> / / Generate code for copying a large number of characters . This function <nl> / / is allowed to spend extra time setting up conditions to make copying <nl> / / faster . Copying of overlapping regions is not supported . <nl> + / / Dest register ends at the position after the last character written . <nl> void GenerateCopyCharactersLong ( MacroAssembler * masm , <nl> Register dest , <nl> Register src , <nl> enum StringAddFlags { <nl> } ; <nl> <nl> <nl> + class StringAddStub : public StringStubBase { <nl> + public : <nl> + explicit StringAddStub ( StringAddFlags flags ) { <nl> + string_check_ = ( ( flags & NO_STRING_CHECK_IN_STUB ) = = 0 ) ; <nl> + } <nl> + <nl> + private : <nl> + Major MajorKey ( ) { return StringAdd ; } <nl> + int MinorKey ( ) { return string_check_ ? 0 : 1 ; } <nl> + <nl> + void Generate ( MacroAssembler * masm ) ; <nl> + <nl> + / / Should the stub check whether arguments are strings ? <nl> + bool string_check_ ; <nl> + } ; <nl> + <nl> + <nl> class SubStringStub : public StringStubBase { <nl> public : <nl> SubStringStub ( ) { } <nl> mmm a / src / arm / macro - assembler - arm . cc <nl> ppp b / src / arm / macro - assembler - arm . cc <nl> void MacroAssembler : : AllocateAsciiString ( Register result , <nl> } <nl> <nl> <nl> + void MacroAssembler : : AllocateTwoByteConsString ( Register result , <nl> + Register length , <nl> + Register scratch1 , <nl> + Register scratch2 , <nl> + Label * gc_required ) { <nl> + AllocateInNewSpace ( ConsString : : kSize / kPointerSize , <nl> + result , <nl> + scratch1 , <nl> + scratch2 , <nl> + gc_required , <nl> + TAG_OBJECT ) ; <nl> + LoadRoot ( scratch1 , Heap : : kConsStringMapRootIndex ) ; <nl> + mov ( scratch2 , Operand ( String : : kEmptyHashField ) ) ; <nl> + str ( length , FieldMemOperand ( result , String : : kLengthOffset ) ) ; <nl> + str ( scratch1 , FieldMemOperand ( result , HeapObject : : kMapOffset ) ) ; <nl> + str ( scratch2 , FieldMemOperand ( result , String : : kHashFieldOffset ) ) ; <nl> + } <nl> + <nl> + <nl> + void MacroAssembler : : AllocateAsciiConsString ( Register result , <nl> + Register length , <nl> + Register scratch1 , <nl> + Register scratch2 , <nl> + Label * gc_required ) { <nl> + AllocateInNewSpace ( ConsString : : kSize / kPointerSize , <nl> + result , <nl> + scratch1 , <nl> + scratch2 , <nl> + gc_required , <nl> + TAG_OBJECT ) ; <nl> + LoadRoot ( scratch1 , Heap : : kConsAsciiStringMapRootIndex ) ; <nl> + mov ( scratch2 , Operand ( String : : kEmptyHashField ) ) ; <nl> + str ( length , FieldMemOperand ( result , String : : kLengthOffset ) ) ; <nl> + str ( scratch1 , FieldMemOperand ( result , HeapObject : : kMapOffset ) ) ; <nl> + str ( scratch2 , FieldMemOperand ( result , String : : kHashFieldOffset ) ) ; <nl> + } <nl> + <nl> + <nl> void MacroAssembler : : CompareObjectType ( Register function , <nl> Register map , <nl> Register type_reg , <nl> void MacroAssembler : : CallStub ( CodeStub * stub , Condition cond ) { <nl> } <nl> <nl> <nl> + void MacroAssembler : : TailCallStub ( CodeStub * stub , Condition cond ) { <nl> + ASSERT ( allow_stub_calls ( ) ) ; / / stub calls are not allowed in some stubs <nl> + Jump ( stub - > GetCode ( ) , RelocInfo : : CODE_TARGET , cond ) ; <nl> + } <nl> + <nl> + <nl> void MacroAssembler : : StubReturn ( int argc ) { <nl> ASSERT ( argc > = 1 & & generating_stub ( ) ) ; <nl> - if ( argc > 1 ) <nl> + if ( argc > 1 ) { <nl> add ( sp , sp , Operand ( ( argc - 1 ) * kPointerSize ) ) ; <nl> + } <nl> Ret ( ) ; <nl> } <nl> <nl> void MacroAssembler : : LoadContext ( Register dst , int context_chain_length ) { <nl> } <nl> <nl> <nl> + void MacroAssembler : : JumpIfNotBothSmi ( Register reg1 , <nl> + Register reg2 , <nl> + Label * on_not_both_smi ) { <nl> + ASSERT_EQ ( 0 , kSmiTag ) ; <nl> + tst ( reg1 , Operand ( kSmiTagMask ) ) ; <nl> + tst ( reg2 , Operand ( kSmiTagMask ) , eq ) ; <nl> + b ( ne , on_not_both_smi ) ; <nl> + } <nl> + <nl> + <nl> + void MacroAssembler : : JumpIfEitherSmi ( Register reg1 , <nl> + Register reg2 , <nl> + Label * on_either_smi ) { <nl> + ASSERT_EQ ( 0 , kSmiTag ) ; <nl> + tst ( reg1 , Operand ( kSmiTagMask ) ) ; <nl> + tst ( reg2 , Operand ( kSmiTagMask ) , ne ) ; <nl> + b ( eq , on_either_smi ) ; <nl> + } <nl> + <nl> + <nl> void MacroAssembler : : JumpIfNonSmisNotBothSequentialAsciiStrings ( <nl> Register first , <nl> Register second , <nl> mmm a / src / arm / macro - assembler - arm . h <nl> ppp b / src / arm / macro - assembler - arm . h <nl> class MacroAssembler : public Assembler { <nl> Register scratch2 , <nl> Register scratch3 , <nl> Label * gc_required ) ; <nl> + void AllocateTwoByteConsString ( Register result , <nl> + Register length , <nl> + Register scratch1 , <nl> + Register scratch2 , <nl> + Label * gc_required ) ; <nl> + void AllocateAsciiConsString ( Register result , <nl> + Register length , <nl> + Register scratch1 , <nl> + Register scratch2 , <nl> + Label * gc_required ) ; <nl> <nl> <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm <nl> class MacroAssembler : public Assembler { <nl> / / Call a code stub . <nl> void CallStub ( CodeStub * stub , Condition cond = al ) ; <nl> <nl> + / / Call a code stub . <nl> + void TailCallStub ( CodeStub * stub , Condition cond = al ) ; <nl> + <nl> / / Return from a code stub after popping its arguments . <nl> void StubReturn ( int argc ) ; <nl> <nl> class MacroAssembler : public Assembler { <nl> void set_allow_stub_calls ( bool value ) { allow_stub_calls_ = value ; } <nl> bool allow_stub_calls ( ) { return allow_stub_calls_ ; } <nl> <nl> + / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm <nl> + / / Smi utilities <nl> + <nl> + / / Jump if either of the registers contain a non - smi . <nl> + void JumpIfNotBothSmi ( Register reg1 , Register reg2 , Label * on_not_both_smi ) ; <nl> + / / Jump if either of the registers contain a smi . <nl> + void JumpIfEitherSmi ( Register reg1 , Register reg2 , Label * on_either_smi ) ; <nl> + <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm <nl> / / String utilities <nl> <nl> mmm a / src / ia32 / codegen - ia32 . h <nl> ppp b / src / ia32 / codegen - ia32 . h <nl> class GenericBinaryOpStub : public CodeStub { <nl> } ; <nl> <nl> <nl> - / / Flag that indicates how to generate code for the stub StringAddStub . <nl> - enum StringAddFlags { <nl> - NO_STRING_ADD_FLAGS = 0 , <nl> - NO_STRING_CHECK_IN_STUB = 1 < < 0 / / Omit string check in stub . <nl> - } ; <nl> - <nl> - <nl> class StringStubBase : public CodeStub { <nl> public : <nl> / / Generate code for copying characters using a simple loop . This should only <nl> class StringStubBase : public CodeStub { <nl> } ; <nl> <nl> <nl> + / / Flag that indicates how to generate code for the stub StringAddStub . <nl> + enum StringAddFlags { <nl> + NO_STRING_ADD_FLAGS = 0 , <nl> + NO_STRING_CHECK_IN_STUB = 1 < < 0 / / Omit string check in stub . <nl> + } ; <nl> + <nl> + <nl> class StringAddStub : public StringStubBase { <nl> public : <nl> explicit StringAddStub ( StringAddFlags flags ) { <nl>
ARM native string addition .
v8/v8
dd85270967695935639aee6df7263e52519d159a
2010-02-05T12:00:42Z
mmm a / cocos / ui / UIEditBox / UIEditBoxImpl - ios . mm <nl> ppp b / cocos / ui / UIEditBox / UIEditBoxImpl - ios . mm <nl> of this software and associated documentation files ( the " Software " ) , to deal <nl> float retinaFactor = eaglview . contentScaleFactor ; <nl> NSString * fntName = [ NSString stringWithUTF8String : fontName ] ; <nl> <nl> + fntName = [ [ fntName lastPathComponent ] stringByDeletingPathExtension ] ; <nl> + <nl> auto glview = cocos2d : : Director : : getInstance ( ) - > getOpenGLView ( ) ; <nl> float scaleFactor = glview - > getScaleX ( ) ; <nl> <nl> mmm a / cocos / ui / UIEditBox / UIEditBoxImpl - mac . mm <nl> ppp b / cocos / ui / UIEditBox / UIEditBoxImpl - mac . mm <nl> - ( void ) controlTextDidChange : ( NSNotification * ) notification <nl> NSFont * EditBoxImplMac : : constructFont ( const char * fontName , int fontSize ) <nl> { <nl> NSString * fntName = [ NSString stringWithUTF8String : fontName ] ; <nl> + fntName = [ [ fntName lastPathComponent ] stringByDeletingPathExtension ] ; <nl> float retinaFactor = _inRetinaMode ? 2 . 0f : 1 . 0f ; <nl> auto glview = cocos2d : : Director : : getInstance ( ) - > getOpenGLView ( ) ; <nl> float scaleFactor = glview - > getScaleX ( ) ; <nl>
Merge pull request from newnon / v3 . 10_editbox_ios_mac_fix
cocos2d/cocos2d-x
841ad8ae9978c6d6575eccd36479e9e24ca02d2b
2016-01-21T03:05:12Z
mmm a / examples / sdl_opengl2_example / build_win32 . bat <nl> ppp b / examples / sdl_opengl2_example / build_win32 . bat <nl> <nl> @ REM Build for Visual Studio compiler . Run your copy of vcvars32 . bat or vcvarsall . bat to setup command - line compiler . <nl> mkdir Debug <nl> - cl / nologo / Zi / MD / I . . \ . . / I . . \ libs \ gl3w / I % SDL_DIR % \ include main . cpp imgui_impl_sdl_gl2 . cpp . . \ . . \ imgui * . cpp . . \ libs \ gl3w \ GL \ gl3w . c / FeDebug / sdl_opengl2_example . exe / FoDebug / / link / libpath : % SDL_DIR % \ lib \ x86 SDL2 . lib SDL2main . lib opengl32 . lib / subsystem : console <nl> + cl / nologo / Zi / MD / I . . \ . . / I . . \ libs \ gl3w / I % SDL2_DIR % \ include main . cpp imgui_impl_sdl_gl2 . cpp . . \ . . \ imgui * . cpp . . \ libs \ gl3w \ GL \ gl3w . c / FeDebug / sdl_opengl2_example . exe / FoDebug / / link / libpath : % SDL2_DIR % \ lib \ x86 SDL2 . lib SDL2main . lib opengl32 . lib / subsystem : console <nl> mmm a / examples / sdl_opengl2_example / sdl_opengl2_example . vcxproj <nl> ppp b / examples / sdl_opengl2_example / sdl_opengl2_example . vcxproj <nl> <nl> < ClCompile > <nl> < WarningLevel > Level4 < / WarningLevel > <nl> < Optimization > Disabled < / Optimization > <nl> - < AdditionalIncludeDirectories > % SDL_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > % SDL2_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < / ClCompile > <nl> < Link > <nl> < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> - < AdditionalLibraryDirectories > % SDL_DIR % \ lib \ x86 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> + < AdditionalLibraryDirectories > % SDL2_DIR % \ lib \ x86 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> < AdditionalDependencies > opengl32 . lib ; SDL2 . lib ; SDL2main . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> < SubSystem > Console < / SubSystem > <nl> < IgnoreSpecificDefaultLibraries > msvcrt . lib < / IgnoreSpecificDefaultLibraries > <nl> <nl> < ClCompile > <nl> < WarningLevel > Level4 < / WarningLevel > <nl> < Optimization > Disabled < / Optimization > <nl> - < AdditionalIncludeDirectories > % SDL_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > % SDL2_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < / ClCompile > <nl> < Link > <nl> < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> - < AdditionalLibraryDirectories > % SDL_DIR % \ lib \ x64 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> + < AdditionalLibraryDirectories > % SDL2_DIR % \ lib \ x64 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> < AdditionalDependencies > opengl32 . lib ; SDL2 . lib ; SDL2main . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> < SubSystem > Console < / SubSystem > <nl> < IgnoreSpecificDefaultLibraries > msvcrt . lib < / IgnoreSpecificDefaultLibraries > <nl> <nl> < Optimization > MaxSpeed < / Optimization > <nl> < FunctionLevelLinking > true < / FunctionLevelLinking > <nl> < IntrinsicFunctions > true < / IntrinsicFunctions > <nl> - < AdditionalIncludeDirectories > % SDL_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > % SDL2_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < BufferSecurityCheck > false < / BufferSecurityCheck > <nl> < / ClCompile > <nl> < Link > <nl> < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> < EnableCOMDATFolding > true < / EnableCOMDATFolding > <nl> < OptimizeReferences > true < / OptimizeReferences > <nl> - < AdditionalLibraryDirectories > % SDL_DIR % \ lib \ x86 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> + < AdditionalLibraryDirectories > % SDL2_DIR % \ lib \ x86 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> < AdditionalDependencies > opengl32 . lib ; SDL2 . lib ; SDL2main . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> < SubSystem > Console < / SubSystem > <nl> < IgnoreSpecificDefaultLibraries > <nl> <nl> < Optimization > MaxSpeed < / Optimization > <nl> < FunctionLevelLinking > true < / FunctionLevelLinking > <nl> < IntrinsicFunctions > true < / IntrinsicFunctions > <nl> - < AdditionalIncludeDirectories > % SDL_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > % SDL2_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < BufferSecurityCheck > false < / BufferSecurityCheck > <nl> < / ClCompile > <nl> < Link > <nl> < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> < EnableCOMDATFolding > true < / EnableCOMDATFolding > <nl> < OptimizeReferences > true < / OptimizeReferences > <nl> - < AdditionalLibraryDirectories > % SDL_DIR % \ lib \ x64 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> + < AdditionalLibraryDirectories > % SDL2_DIR % \ lib \ x64 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> < AdditionalDependencies > opengl32 . lib ; SDL2 . lib ; SDL2main . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> < SubSystem > Console < / SubSystem > <nl> < IgnoreSpecificDefaultLibraries > <nl> mmm a / examples / sdl_opengl3_example / build_win32 . bat <nl> ppp b / examples / sdl_opengl3_example / build_win32 . bat <nl> <nl> @ REM Build for Visual Studio compiler . Run your copy of vcvars32 . bat or vcvarsall . bat to setup command - line compiler . <nl> mkdir Debug <nl> - cl / nologo / Zi / MD / I . . \ . . / I . . \ libs \ gl3w / I % SDL_DIR % \ include main . cpp imgui_impl_sdl_gl3 . cpp . . \ . . \ imgui * . cpp . . \ libs \ gl3w \ GL \ gl3w . c / FeDebug / sdl_opengl3_example . exe / FoDebug / / link / libpath : % SDL_DIR % \ lib \ x86 SDL2 . lib SDL2main . lib opengl32 . lib / subsystem : console <nl> + cl / nologo / Zi / MD / I . . \ . . / I . . \ libs \ gl3w / I % SDL2_DIR % \ include main . cpp imgui_impl_sdl_gl3 . cpp . . \ . . \ imgui * . cpp . . \ libs \ gl3w \ GL \ gl3w . c / FeDebug / sdl_opengl3_example . exe / FoDebug / / link / libpath : % SDL2_DIR % \ lib \ x86 SDL2 . lib SDL2main . lib opengl32 . lib / subsystem : console <nl> mmm a / examples / sdl_opengl3_example / sdl_opengl3_example . vcxproj <nl> ppp b / examples / sdl_opengl3_example / sdl_opengl3_example . vcxproj <nl> <nl> < ClCompile > <nl> < WarningLevel > Level4 < / WarningLevel > <nl> < Optimization > Disabled < / Optimization > <nl> - < AdditionalIncludeDirectories > % SDL_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > % SDL2_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < / ClCompile > <nl> < Link > <nl> < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> - < AdditionalLibraryDirectories > % SDL_DIR % \ lib \ x86 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> + < AdditionalLibraryDirectories > % SDL2_DIR % \ lib \ x86 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> < AdditionalDependencies > opengl32 . lib ; SDL2 . lib ; SDL2main . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> < SubSystem > Console < / SubSystem > <nl> < IgnoreSpecificDefaultLibraries > msvcrt . lib < / IgnoreSpecificDefaultLibraries > <nl> <nl> < ClCompile > <nl> < WarningLevel > Level4 < / WarningLevel > <nl> < Optimization > Disabled < / Optimization > <nl> - < AdditionalIncludeDirectories > % SDL_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > % SDL2_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < / ClCompile > <nl> < Link > <nl> < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> - < AdditionalLibraryDirectories > % SDL_DIR % \ lib \ x64 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> + < AdditionalLibraryDirectories > % SDL2_DIR % \ lib \ x64 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> < AdditionalDependencies > opengl32 . lib ; SDL2 . lib ; SDL2main . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> < SubSystem > Console < / SubSystem > <nl> < IgnoreSpecificDefaultLibraries > msvcrt . lib < / IgnoreSpecificDefaultLibraries > <nl> <nl> < Optimization > MaxSpeed < / Optimization > <nl> < FunctionLevelLinking > true < / FunctionLevelLinking > <nl> < IntrinsicFunctions > true < / IntrinsicFunctions > <nl> - < AdditionalIncludeDirectories > % SDL_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > % SDL2_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < BufferSecurityCheck > false < / BufferSecurityCheck > <nl> < / ClCompile > <nl> < Link > <nl> < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> < EnableCOMDATFolding > true < / EnableCOMDATFolding > <nl> < OptimizeReferences > true < / OptimizeReferences > <nl> - < AdditionalLibraryDirectories > % SDL_DIR % \ lib \ x86 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> + < AdditionalLibraryDirectories > % SDL2_DIR % \ lib \ x86 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> < AdditionalDependencies > opengl32 . lib ; SDL2 . lib ; SDL2main . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> < SubSystem > Console < / SubSystem > <nl> < IgnoreSpecificDefaultLibraries > <nl> <nl> < Optimization > MaxSpeed < / Optimization > <nl> < FunctionLevelLinking > true < / FunctionLevelLinking > <nl> < IntrinsicFunctions > true < / IntrinsicFunctions > <nl> - < AdditionalIncludeDirectories > % SDL_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > % SDL2_DIR % \ include ; $ ( SolutionDir ) \ libs \ gl3w ; . . \ . . ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < BufferSecurityCheck > false < / BufferSecurityCheck > <nl> < / ClCompile > <nl> < Link > <nl> < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> < EnableCOMDATFolding > true < / EnableCOMDATFolding > <nl> < OptimizeReferences > true < / OptimizeReferences > <nl> - < AdditionalLibraryDirectories > % SDL_DIR % \ lib \ x64 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> + < AdditionalLibraryDirectories > % SDL2_DIR % \ lib \ x64 ; % ( AdditionalLibraryDirectories ) < / AdditionalLibraryDirectories > <nl> < AdditionalDependencies > opengl32 . lib ; SDL2 . lib ; SDL2main . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> < SubSystem > Console < / SubSystem > <nl> < IgnoreSpecificDefaultLibraries > <nl>
Examples : SDL : Using % SDL2_DIR % in the . vcproj instead of % SDL_DIR % , the earlier is more standard .
ocornut/imgui
9b9d9321cf08253eae5b13d8f14d7ceb162efdf7
2018-02-21T21:46:49Z
mmm a / lib / Dispatcher / DispatcherThread . cpp <nl> ppp b / lib / Dispatcher / DispatcherThread . cpp <nl> void DispatcherThread : : run ( ) { <nl> } <nl> catch ( std : : exception const & ex ) { <nl> try { <nl> - Exception ex ( TRI_ERROR_INTERNAL , string ( " job failed with unknown in work : " ) + ex . what ( ) , __FILE__ , __LINE__ ) ; <nl> + Exception ex2 ( TRI_ERROR_INTERNAL , string ( " job failed with unknown in work : " ) + ex . what ( ) , __FILE__ , __LINE__ ) ; <nl> <nl> - job - > handleError ( ex ) ; <nl> + job - > handleError ( ex2 ) ; <nl> } <nl> catch ( Exception const & ex ) { <nl> LOG_WARNING ( " caught error while handling error : % s " , ex . what ( ) ) ; <nl>
fixed variable usage
arangodb/arangodb
0254bb50f45a043785cd5885a7008a0d2d904128
2015-05-06T07:46:17Z
mmm a / src / compiler / x64 / instruction - selector - x64 . cc <nl> ppp b / src / compiler / x64 / instruction - selector - x64 . cc <nl> class X64OperandGenerator final : public OperandGenerator { <nl> } <nl> } <nl> } <nl> + if ( operand - > InputCount ( ) = = 2 ) { <nl> + Node * left = operand - > InputAt ( 0 ) ; <nl> + Node * right = operand - > InputAt ( 1 ) ; <nl> + if ( left - > opcode ( ) = = IrOpcode : : kLoadRootsPointer & & <nl> + right - > opcode ( ) = = IrOpcode : : kInt64Constant ) { <nl> + int64_t offset = OpParameter < int64_t > ( right - > op ( ) ) ; <nl> + DCHECK ( is_int32 ( offset ) ) ; <nl> + inputs [ ( * input_count ) + + ] = TempImmediate ( static_cast < int32_t > ( offset ) ) ; <nl> + return kMode_Root ; <nl> + } <nl> + } <nl> BaseWithIndexAndDisplacement64Matcher m ( operand , AddressOption : : kAllowAll ) ; <nl> DCHECK ( m . matches ( ) ) ; <nl> if ( m . displacement ( ) = = nullptr | | CanBeImmediate ( m . displacement ( ) ) ) { <nl>
[ turbofan ] [ x64 ] Reduce reg - to - reg moving instruction for LoadRootsRegister IR
v8/v8
d4177d117388a3a5e9023495ba81929b4ec28dfd
2018-03-28T09:51:25Z
mmm a / src / arm / builtins - arm . cc <nl> ppp b / src / arm / builtins - arm . cc <nl> void Builtins : : Generate_ResumeGeneratorTrampoline ( MacroAssembler * masm ) { <nl> __ bind ( & done_loop ) ; <nl> } <nl> <nl> - / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> - / / the generator was suspended . <nl> - DCHECK ( ! FLAG_enable_embedded_constant_pool ) ; <nl> - FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> - __ Push ( lr , fp ) ; <nl> - __ Move ( fp , sp ) ; <nl> - __ Push ( cp , r4 ) ; <nl> - <nl> - / / Restore the operand stack . <nl> - __ ldr ( r0 , FieldMemOperand ( r1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> - __ ldr ( r3 , FieldMemOperand ( r0 , FixedArray : : kLengthOffset ) ) ; <nl> - __ add ( r0 , r0 , Operand ( FixedArray : : kHeaderSize - kHeapObjectTag ) ) ; <nl> - __ add ( r3 , r0 , Operand ( r3 , LSL , kPointerSizeLog2 - 1 ) ) ; <nl> + / / Dispatch on the kind of generator object . <nl> + Label old_generator ; <nl> + __ ldr ( r3 , FieldMemOperand ( r4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ ldr ( r3 , FieldMemOperand ( r3 , SharedFunctionInfo : : kFunctionDataOffset ) ) ; <nl> + __ CompareObjectType ( r3 , r3 , r3 , BYTECODE_ARRAY_TYPE ) ; <nl> + __ b ( ne , & old_generator ) ; <nl> + <nl> + / / New - style ( ignition / turbofan ) generator object <nl> { <nl> - Label done_loop , loop ; <nl> - __ bind ( & loop ) ; <nl> - __ cmp ( r0 , r3 ) ; <nl> - __ b ( eq , & done_loop ) ; <nl> - __ ldr ( ip , MemOperand ( r0 , kPointerSize , PostIndex ) ) ; <nl> - __ Push ( ip ) ; <nl> - __ b ( & loop ) ; <nl> - __ bind ( & done_loop ) ; <nl> + __ ldr ( r0 , FieldMemOperand ( r4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ ldr ( r0 , <nl> + FieldMemOperand ( r0 , SharedFunctionInfo : : kFormalParameterCountOffset ) ) ; <nl> + __ SmiUntag ( r0 ) ; <nl> + / / We abuse new . target both to indicate that this is a resume call and to <nl> + / / pass in the generator object . In ordinary calls , new . target is always <nl> + / / undefined because generator functions are non - constructable . <nl> + __ Move ( r3 , r1 ) ; <nl> + __ Move ( r1 , r4 ) ; <nl> + __ ldr ( r5 , FieldMemOperand ( r1 , JSFunction : : kCodeEntryOffset ) ) ; <nl> + __ Jump ( r5 ) ; <nl> } <nl> <nl> - / / Reset operand stack so we don ' t leak . <nl> - __ LoadRoot ( ip , Heap : : kEmptyFixedArrayRootIndex ) ; <nl> - __ str ( ip , FieldMemOperand ( r1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + / / Old - style ( full - codegen ) generator object <nl> + __ bind ( & old_generator ) ; <nl> + { <nl> + / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> + / / the generator was suspended . <nl> + DCHECK ( ! FLAG_enable_embedded_constant_pool ) ; <nl> + FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> + __ Push ( lr , fp ) ; <nl> + __ Move ( fp , sp ) ; <nl> + __ Push ( cp , r4 ) ; <nl> + <nl> + / / Restore the operand stack . <nl> + __ ldr ( r0 , FieldMemOperand ( r1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + __ ldr ( r3 , FieldMemOperand ( r0 , FixedArray : : kLengthOffset ) ) ; <nl> + __ add ( r0 , r0 , Operand ( FixedArray : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + __ add ( r3 , r0 , Operand ( r3 , LSL , kPointerSizeLog2 - 1 ) ) ; <nl> + { <nl> + Label done_loop , loop ; <nl> + __ bind ( & loop ) ; <nl> + __ cmp ( r0 , r3 ) ; <nl> + __ b ( eq , & done_loop ) ; <nl> + __ ldr ( ip , MemOperand ( r0 , kPointerSize , PostIndex ) ) ; <nl> + __ Push ( ip ) ; <nl> + __ b ( & loop ) ; <nl> + __ bind ( & done_loop ) ; <nl> + } <nl> <nl> - / / Resume the generator function at the continuation . <nl> - __ ldr ( r3 , FieldMemOperand ( r4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> - __ ldr ( r3 , FieldMemOperand ( r3 , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> - __ add ( r3 , r3 , Operand ( Code : : kHeaderSize - kHeapObjectTag ) ) ; <nl> - __ ldr ( r2 , FieldMemOperand ( r1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> - __ add ( r3 , r3 , Operand ( r2 , ASR , 1 ) ) ; <nl> - __ mov ( r2 , Operand ( Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ) ; <nl> - __ str ( r2 , FieldMemOperand ( r1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> - __ Move ( r0 , r1 ) ; / / Continuation expects generator object in r0 . <nl> - __ Jump ( r3 ) ; <nl> + / / Reset operand stack so we don ' t leak . <nl> + __ LoadRoot ( ip , Heap : : kEmptyFixedArrayRootIndex ) ; <nl> + __ str ( ip , FieldMemOperand ( r1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + <nl> + / / Resume the generator function at the continuation . <nl> + __ ldr ( r3 , FieldMemOperand ( r4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ ldr ( r3 , FieldMemOperand ( r3 , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> + __ add ( r3 , r3 , Operand ( Code : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + __ ldr ( r2 , FieldMemOperand ( r1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> + __ add ( r3 , r3 , Operand ( r2 , ASR , 1 ) ) ; <nl> + __ mov ( r2 , Operand ( Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ) ; <nl> + __ str ( r2 , FieldMemOperand ( r1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> + __ Move ( r0 , r1 ) ; / / Continuation expects generator object in r0 . <nl> + __ Jump ( r3 ) ; <nl> + } <nl> } <nl> <nl> void Builtins : : Generate_ConstructedNonConstructable ( MacroAssembler * masm ) { <nl> mmm a / src / arm64 / builtins - arm64 . cc <nl> ppp b / src / arm64 / builtins - arm64 . cc <nl> void Builtins : : Generate_ResumeGeneratorTrampoline ( MacroAssembler * masm ) { <nl> / / values have already been copied into the context and these dummy values <nl> / / will never be used . <nl> __ Ldr ( x10 , FieldMemOperand ( x4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> - <nl> - / / Push holes for arguments to generator function . Since the parser forced <nl> - / / context allocation for any variables in generators , the actual argument <nl> - / / values have already been copied into the context and these dummy values <nl> - / / will never be used . <nl> __ Ldr ( w10 , <nl> FieldMemOperand ( x10 , SharedFunctionInfo : : kFormalParameterCountOffset ) ) ; <nl> __ LoadRoot ( x11 , Heap : : kTheHoleValueRootIndex ) ; <nl> __ PushMultipleTimes ( x11 , w10 ) ; <nl> <nl> - / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> - / / the generator was suspended . <nl> - FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> - __ Push ( lr , fp ) ; <nl> - __ Move ( fp , jssp ) ; <nl> - __ Push ( cp , x4 ) ; <nl> - <nl> - / / Restore the operand stack . <nl> - __ Ldr ( x0 , FieldMemOperand ( x1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> - __ Ldr ( w3 , UntagSmiFieldMemOperand ( x0 , FixedArray : : kLengthOffset ) ) ; <nl> - __ Add ( x0 , x0 , Operand ( FixedArray : : kHeaderSize - kHeapObjectTag ) ) ; <nl> - __ Add ( x3 , x0 , Operand ( x3 , LSL , kPointerSizeLog2 ) ) ; <nl> + / / Dispatch on the kind of generator object . <nl> + Label old_generator ; <nl> + __ Ldr ( x3 , FieldMemOperand ( x4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ Ldr ( x3 , FieldMemOperand ( x3 , SharedFunctionInfo : : kFunctionDataOffset ) ) ; <nl> + __ CompareObjectType ( x3 , x3 , x3 , BYTECODE_ARRAY_TYPE ) ; <nl> + __ B ( ne , & old_generator ) ; <nl> + <nl> + / / New - style ( ignition / turbofan ) generator object <nl> { <nl> - Label done_loop , loop ; <nl> - __ Bind ( & loop ) ; <nl> - __ Cmp ( x0 , x3 ) ; <nl> - __ B ( eq , & done_loop ) ; <nl> - __ Ldr ( x10 , MemOperand ( x0 , kPointerSize , PostIndex ) ) ; <nl> - __ Push ( x10 ) ; <nl> - __ B ( & loop ) ; <nl> - __ Bind ( & done_loop ) ; <nl> + __ Ldr ( x0 , FieldMemOperand ( x4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ Ldr ( x0 , <nl> + FieldMemOperand ( x0 , SharedFunctionInfo : : kFormalParameterCountOffset ) ) ; <nl> + __ SmiUntag ( x0 ) ; <nl> + / / We abuse new . target both to indicate that this is a resume call and to <nl> + / / pass in the generator object . In ordinary calls , new . target is always <nl> + / / undefined because generator functions are non - constructable . <nl> + __ Move ( x3 , x1 ) ; <nl> + __ Move ( x1 , x4 ) ; <nl> + __ Ldr ( x5 , FieldMemOperand ( x1 , JSFunction : : kCodeEntryOffset ) ) ; <nl> + __ Jump ( x5 ) ; <nl> } <nl> <nl> - / / Reset operand stack so we don ' t leak . <nl> - __ LoadRoot ( x10 , Heap : : kEmptyFixedArrayRootIndex ) ; <nl> - __ Str ( x10 , FieldMemOperand ( x1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + / / Old - style ( full - codegen ) generator object <nl> + __ bind ( & old_generator ) ; <nl> + { <nl> + / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> + / / the generator was suspended . <nl> + FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> + __ Push ( lr , fp ) ; <nl> + __ Move ( fp , jssp ) ; <nl> + __ Push ( cp , x4 ) ; <nl> + <nl> + / / Restore the operand stack . <nl> + __ Ldr ( x0 , FieldMemOperand ( x1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + __ Ldr ( w3 , UntagSmiFieldMemOperand ( x0 , FixedArray : : kLengthOffset ) ) ; <nl> + __ Add ( x0 , x0 , Operand ( FixedArray : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + __ Add ( x3 , x0 , Operand ( x3 , LSL , kPointerSizeLog2 ) ) ; <nl> + { <nl> + Label done_loop , loop ; <nl> + __ Bind ( & loop ) ; <nl> + __ Cmp ( x0 , x3 ) ; <nl> + __ B ( eq , & done_loop ) ; <nl> + __ Ldr ( x10 , MemOperand ( x0 , kPointerSize , PostIndex ) ) ; <nl> + __ Push ( x10 ) ; <nl> + __ B ( & loop ) ; <nl> + __ Bind ( & done_loop ) ; <nl> + } <nl> <nl> - / / Resume the generator function at the continuation . <nl> - __ Ldr ( x10 , FieldMemOperand ( x4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> - __ Ldr ( x10 , FieldMemOperand ( x10 , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> - __ Add ( x10 , x10 , Code : : kHeaderSize - kHeapObjectTag ) ; <nl> - __ Ldrsw ( x11 , <nl> - UntagSmiFieldMemOperand ( x1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> - __ Add ( x10 , x10 , x11 ) ; <nl> - __ Mov ( x12 , Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ; <nl> - __ Str ( x12 , FieldMemOperand ( x1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> - __ Move ( x0 , x1 ) ; / / Continuation expects generator object in x0 . <nl> - __ Br ( x10 ) ; <nl> + / / Reset operand stack so we don ' t leak . <nl> + __ LoadRoot ( x10 , Heap : : kEmptyFixedArrayRootIndex ) ; <nl> + __ Str ( x10 , FieldMemOperand ( x1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + <nl> + / / Resume the generator function at the continuation . <nl> + __ Ldr ( x10 , FieldMemOperand ( x4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ Ldr ( x10 , FieldMemOperand ( x10 , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> + __ Add ( x10 , x10 , Code : : kHeaderSize - kHeapObjectTag ) ; <nl> + __ Ldrsw ( x11 , <nl> + UntagSmiFieldMemOperand ( x1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> + __ Add ( x10 , x10 , x11 ) ; <nl> + __ Mov ( x12 , Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ; <nl> + __ Str ( x12 , FieldMemOperand ( x1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> + __ Move ( x0 , x1 ) ; / / Continuation expects generator object in x0 . <nl> + __ Br ( x10 ) ; <nl> + } <nl> } <nl> <nl> enum IsTagged { kArgcIsSmiTagged , kArgcIsUntaggedInt } ; <nl> mmm a / src / builtins . cc <nl> ppp b / src / builtins . cc <nl> void Generate_GeneratorPrototypeResume ( <nl> Node * receiver = assembler - > Parameter ( 0 ) ; <nl> Node * value = assembler - > Parameter ( 1 ) ; <nl> Node * context = assembler - > Parameter ( 4 ) ; <nl> - Node * zero = assembler - > SmiConstant ( Smi : : FromInt ( 0 ) ) ; <nl> + Node * closed = assembler - > SmiConstant ( <nl> + Smi : : FromInt ( JSGeneratorObject : : kGeneratorClosed ) ) ; <nl> <nl> / / Check if the { receiver } is actually a JSGeneratorObject . <nl> Label if_receiverisincompatible ( assembler , Label : : kDeferred ) ; <nl> void Generate_GeneratorPrototypeResume ( <nl> receiver , JSGeneratorObject : : kContinuationOffset ) ; <nl> Label if_receiverisclosed ( assembler , Label : : kDeferred ) , <nl> if_receiverisrunning ( assembler , Label : : kDeferred ) ; <nl> - assembler - > GotoIf ( assembler - > SmiEqual ( receiver_continuation , zero ) , <nl> + assembler - > GotoIf ( assembler - > SmiEqual ( receiver_continuation , closed ) , <nl> & if_receiverisclosed ) ; <nl> - assembler - > GotoIf ( assembler - > SmiLessThan ( receiver_continuation , zero ) , <nl> + DCHECK_LT ( JSGeneratorObject : : kGeneratorExecuting , <nl> + JSGeneratorObject : : kGeneratorClosed ) ; <nl> + assembler - > GotoIf ( assembler - > SmiLessThan ( receiver_continuation , closed ) , <nl> & if_receiverisrunning ) ; <nl> <nl> / / Resume the { receiver } using our trampoline . <nl> mmm a / src / compiler . cc <nl> ppp b / src / compiler . cc <nl> bool UseIgnition ( CompilationInfo * info ) { <nl> return false ; <nl> } <nl> <nl> - / / TODO ( 4681 ) : Generator functions are not yet supported . <nl> - if ( info - > shared_info ( ) - > is_generator ( ) ) { <nl> + if ( info - > shared_info ( ) - > is_generator ( ) & & ! FLAG_ignition_generators ) { <nl> return false ; <nl> } <nl> <nl> MaybeHandle < Code > GetOptimizedCode ( Handle < JSFunction > function , <nl> return MaybeHandle < Code > ( ) ; <nl> } <nl> <nl> + / / Do not use Crankshaft / TurboFan on a generator function . <nl> + / / TODO ( neis ) : Eventually enable for Turbofan . <nl> + if ( IsGeneratorFunction ( info - > shared_info ( ) - > kind ( ) ) ) { <nl> + info - > AbortOptimization ( kGenerator ) ; <nl> + return MaybeHandle < Code > ( ) ; <nl> + } <nl> + <nl> / / Limit the number of times we try to optimize functions . <nl> const int kMaxOptCount = <nl> FLAG_deopt_every_n_times = = 0 ? FLAG_max_opt_count : 1000 ; <nl> mmm a / src / debug / mirrors . js <nl> ppp b / src / debug / mirrors . js <nl> inherits ( GeneratorMirror , ObjectMirror ) ; <nl> <nl> function GeneratorGetStatus_ ( value ) { <nl> var continuation = % GeneratorGetContinuation ( value ) ; <nl> - if ( continuation < 0 ) return " running " ; <nl> - if ( continuation = = 0 ) return " closed " ; <nl> + if ( continuation < - 1 ) return " running " ; <nl> + if ( continuation = = - 1 ) return " closed " ; <nl> return " suspended " ; <nl> } <nl> <nl> mmm a / src / flag - definitions . h <nl> ppp b / src / flag - definitions . h <nl> DEFINE_BOOL ( string_slices , true , " use string slices " ) <nl> / / Flags for Ignition . <nl> DEFINE_BOOL ( ignition , false , " use ignition interpreter " ) <nl> DEFINE_BOOL ( ignition_eager , true , " eagerly compile and parse with ignition " ) <nl> + DEFINE_BOOL ( ignition_generators , false , <nl> + " enable experimental ignition support for generators " ) <nl> DEFINE_STRING ( ignition_filter , " * " , " filter for ignition interpreter " ) <nl> DEFINE_BOOL ( print_bytecode , false , <nl> " print bytecode generated by ignition interpreter " ) <nl> mmm a / src / frames . cc <nl> ppp b / src / frames . cc <nl> void InterpretedFrame : : PatchBytecodeArray ( BytecodeArray * bytecode_array ) { <nl> SetExpression ( index , bytecode_array ) ; <nl> } <nl> <nl> - Object * InterpretedFrame : : GetInterpreterRegister ( int register_index ) const { <nl> + Object * InterpretedFrame : : ReadInterpreterRegister ( int register_index ) const { <nl> const int index = InterpreterFrameConstants : : kRegisterFileExpressionIndex ; <nl> DCHECK_EQ ( <nl> InterpreterFrameConstants : : kRegisterFilePointerFromFp , <nl> Object * InterpretedFrame : : GetInterpreterRegister ( int register_index ) const { <nl> return GetExpression ( index + register_index ) ; <nl> } <nl> <nl> + void InterpretedFrame : : WriteInterpreterRegister ( int register_index , <nl> + Object * value ) { <nl> + const int index = InterpreterFrameConstants : : kRegisterFileExpressionIndex ; <nl> + DCHECK_EQ ( <nl> + InterpreterFrameConstants : : kRegisterFilePointerFromFp , <nl> + InterpreterFrameConstants : : kExpressionsOffset - index * kPointerSize ) ; <nl> + return SetExpression ( index + register_index , value ) ; <nl> + } <nl> + <nl> void InterpretedFrame : : Summarize ( List < FrameSummary > * functions ) const { <nl> DCHECK ( functions - > length ( ) = = 0 ) ; <nl> AbstractCode * abstract_code = <nl> mmm a / src / frames . h <nl> ppp b / src / frames . h <nl> class InterpretedFrame : public JavaScriptFrame { <nl> void PatchBytecodeArray ( BytecodeArray * bytecode_array ) ; <nl> <nl> / / Access to the interpreter register file for this frame . <nl> - Object * GetInterpreterRegister ( int register_index ) const ; <nl> + Object * ReadInterpreterRegister ( int register_index ) const ; <nl> + void WriteInterpreterRegister ( int register_index , Object * value ) ; <nl> <nl> / / Build a list with summaries for this frame including all inlined frames . <nl> void Summarize ( List < FrameSummary > * frames ) const override ; <nl> mmm a / src / ia32 / builtins - ia32 . cc <nl> ppp b / src / ia32 / builtins - ia32 . cc <nl> void Builtins : : Generate_ResumeGeneratorTrampoline ( MacroAssembler * masm ) { <nl> __ bind ( & done_loop ) ; <nl> } <nl> <nl> - / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> - / / the generator was suspended . <nl> - FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> - __ PushReturnAddressFrom ( eax ) ; / / Return address . <nl> - __ Push ( ebp ) ; / / Caller ' s frame pointer . <nl> - __ Move ( ebp , esp ) ; <nl> - __ Push ( esi ) ; / / Callee ' s context . <nl> - __ Push ( edi ) ; / / Callee ' s JS Function . <nl> - <nl> - / / Restore the operand stack . <nl> - __ mov ( eax , FieldOperand ( ebx , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + / / Dispatch on the kind of generator object . <nl> + Label old_generator ; <nl> + __ mov ( ecx , FieldOperand ( edi , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ mov ( ecx , FieldOperand ( ecx , SharedFunctionInfo : : kFunctionDataOffset ) ) ; <nl> + __ CmpObjectType ( ecx , BYTECODE_ARRAY_TYPE , ecx ) ; <nl> + __ j ( not_equal , & old_generator ) ; <nl> + <nl> + / / New - style ( ignition / turbofan ) generator object <nl> { <nl> - Label done_loop , loop ; <nl> - __ Move ( ecx , Smi : : FromInt ( 0 ) ) ; <nl> - __ bind ( & loop ) ; <nl> - __ cmp ( ecx , FieldOperand ( eax , FixedArray : : kLengthOffset ) ) ; <nl> - __ j ( equal , & done_loop , Label : : kNear ) ; <nl> - __ Push ( FieldOperand ( eax , ecx , times_half_pointer_size , <nl> - FixedArray : : kHeaderSize ) ) ; <nl> - __ add ( ecx , Immediate ( Smi : : FromInt ( 1 ) ) ) ; <nl> - __ jmp ( & loop ) ; <nl> - __ bind ( & done_loop ) ; <nl> + __ PushReturnAddressFrom ( eax ) ; <nl> + __ mov ( eax , FieldOperand ( edi , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ mov ( eax , <nl> + FieldOperand ( ecx , SharedFunctionInfo : : kFormalParameterCountOffset ) ) ; <nl> + / / We abuse new . target both to indicate that this is a resume call and to <nl> + / / pass in the generator object . In ordinary calls , new . target is always <nl> + / / undefined because generator functions are non - constructable . <nl> + __ mov ( edx , ebx ) ; <nl> + __ jmp ( FieldOperand ( edi , JSFunction : : kCodeEntryOffset ) ) ; <nl> } <nl> <nl> - / / Reset operand stack so we don ' t leak . <nl> - __ mov ( FieldOperand ( ebx , JSGeneratorObject : : kOperandStackOffset ) , <nl> - Immediate ( masm - > isolate ( ) - > factory ( ) - > empty_fixed_array ( ) ) ) ; <nl> + / / Old - style ( full - codegen ) generator object <nl> + __ bind ( & old_generator ) ; <nl> + { <nl> + / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> + / / the generator was suspended . <nl> + FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> + __ PushReturnAddressFrom ( eax ) ; / / Return address . <nl> + __ Push ( ebp ) ; / / Caller ' s frame pointer . <nl> + __ Move ( ebp , esp ) ; <nl> + __ Push ( esi ) ; / / Callee ' s context . <nl> + __ Push ( edi ) ; / / Callee ' s JS Function . <nl> + <nl> + / / Restore the operand stack . <nl> + __ mov ( eax , FieldOperand ( ebx , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + { <nl> + Label done_loop , loop ; <nl> + __ Move ( ecx , Smi : : FromInt ( 0 ) ) ; <nl> + __ bind ( & loop ) ; <nl> + __ cmp ( ecx , FieldOperand ( eax , FixedArray : : kLengthOffset ) ) ; <nl> + __ j ( equal , & done_loop , Label : : kNear ) ; <nl> + __ Push ( FieldOperand ( eax , ecx , times_half_pointer_size , <nl> + FixedArray : : kHeaderSize ) ) ; <nl> + __ add ( ecx , Immediate ( Smi : : FromInt ( 1 ) ) ) ; <nl> + __ jmp ( & loop ) ; <nl> + __ bind ( & done_loop ) ; <nl> + } <nl> <nl> - / / Resume the generator function at the continuation . <nl> - __ mov ( edx , FieldOperand ( edi , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> - __ mov ( edx , FieldOperand ( edx , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> - __ mov ( ecx , FieldOperand ( ebx , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> - __ SmiUntag ( ecx ) ; <nl> - __ lea ( edx , FieldOperand ( edx , ecx , times_1 , Code : : kHeaderSize ) ) ; <nl> - __ mov ( FieldOperand ( ebx , JSGeneratorObject : : kContinuationOffset ) , <nl> - Immediate ( Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ) ; <nl> - __ mov ( eax , ebx ) ; / / Continuation expects generator object in eax . <nl> - __ jmp ( edx ) ; <nl> + / / Reset operand stack so we don ' t leak . <nl> + __ mov ( FieldOperand ( ebx , JSGeneratorObject : : kOperandStackOffset ) , <nl> + Immediate ( masm - > isolate ( ) - > factory ( ) - > empty_fixed_array ( ) ) ) ; <nl> + <nl> + / / Resume the generator function at the continuation . <nl> + __ mov ( edx , FieldOperand ( edi , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ mov ( edx , FieldOperand ( edx , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> + __ mov ( ecx , FieldOperand ( ebx , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> + __ SmiUntag ( ecx ) ; <nl> + __ lea ( edx , FieldOperand ( edx , ecx , times_1 , Code : : kHeaderSize ) ) ; <nl> + __ mov ( FieldOperand ( ebx , JSGeneratorObject : : kContinuationOffset ) , <nl> + Immediate ( Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ) ; <nl> + __ mov ( eax , ebx ) ; / / Continuation expects generator object in eax . <nl> + __ jmp ( edx ) ; <nl> + } <nl> } <nl> <nl> / / Generate code for entering a JS function with the interpreter . <nl> mmm a / src / interpreter / bytecode - array - builder . cc <nl> ppp b / src / interpreter / bytecode - array - builder . cc <nl> BytecodeArrayBuilder & BytecodeArrayBuilder : : Return ( ) { <nl> return * this ; <nl> } <nl> <nl> + BytecodeArrayBuilder & BytecodeArrayBuilder : : Illegal ( ) { <nl> + Output ( Bytecode : : kIllegal ) ; <nl> + return * this ; <nl> + } <nl> + <nl> BytecodeArrayBuilder & BytecodeArrayBuilder : : Debugger ( ) { <nl> Output ( Bytecode : : kDebugger ) ; <nl> return * this ; <nl> mmm a / src / interpreter / bytecode - array - builder . h <nl> ppp b / src / interpreter / bytecode - array - builder . h <nl> class BytecodeArrayBuilder final : public ZoneObject { <nl> BytecodeArrayBuilder & ReThrow ( ) ; <nl> BytecodeArrayBuilder & Return ( ) ; <nl> <nl> + BytecodeArrayBuilder & Illegal ( ) ; <nl> + <nl> / / Debugger . <nl> BytecodeArrayBuilder & Debugger ( ) ; <nl> <nl> mmm a / src / interpreter / bytecode - generator . cc <nl> ppp b / src / interpreter / bytecode - generator . cc <nl> BytecodeGenerator : : BytecodeGenerator ( Isolate * isolate , Zone * zone ) <nl> execution_context_ ( nullptr ) , <nl> execution_result_ ( nullptr ) , <nl> register_allocator_ ( nullptr ) , <nl> + generator_resume_points_ ( 0 , zone ) , <nl> try_catch_nesting_level_ ( 0 ) , <nl> - try_finally_nesting_level_ ( 0 ) { <nl> + try_finally_nesting_level_ ( 0 ) , <nl> + generator_yields_seen_ ( 0 ) { <nl> InitializeAstVisitor ( isolate ) ; <nl> } <nl> <nl> Handle < BytecodeArray > BytecodeGenerator : : MakeBytecode ( CompilationInfo * info ) { <nl> / / Initialize control scope . <nl> ControlScopeForTopLevel control ( this ) ; <nl> <nl> + if ( IsGeneratorFunction ( info - > literal ( ) - > kind ( ) ) ) { <nl> + VisitGeneratorPrologue ( ) ; <nl> + } <nl> + <nl> / / Build function context only if there are context allocated variables . <nl> if ( scope ( ) - > NeedsContext ( ) ) { <nl> / / Push a new inner context scope for the function . <nl> void BytecodeGenerator : : MakeBytecodeBody ( ) { <nl> VisitStatements ( info ( ) - > literal ( ) - > body ( ) ) ; <nl> } <nl> <nl> + void BytecodeGenerator : : VisitGeneratorPrologue ( ) { <nl> + generator_resume_points_ . clear ( ) ; <nl> + generator_resume_points_ . resize ( info ( ) - > literal ( ) - > yield_count ( ) ) ; <nl> + <nl> + BytecodeLabel regular_call ; <nl> + builder ( ) <nl> + - > LoadAccumulatorWithRegister ( Register : : new_target ( ) ) <nl> + . JumpIfUndefined ( & regular_call ) ; <nl> + <nl> + / / This is a resume call . Restore registers and perform state dispatch . <nl> + / / ( The current context has already been restored by the trampoline . ) <nl> + { <nl> + RegisterAllocationScope register_scope ( this ) ; <nl> + Register state = register_allocator ( ) - > NewRegister ( ) ; <nl> + builder ( ) <nl> + - > CallRuntime ( Runtime : : kResumeIgnitionGenerator , Register : : new_target ( ) , <nl> + 1 ) <nl> + . StoreAccumulatorInRegister ( state ) ; <nl> + <nl> + / / TODO ( neis ) : Optimize this by using a proper jump table . <nl> + for ( size_t i = 0 ; i < generator_resume_points_ . size ( ) ; + + i ) { <nl> + builder ( ) <nl> + - > LoadLiteral ( Smi : : FromInt ( static_cast < int > ( i ) ) ) <nl> + . CompareOperation ( Token : : Value : : EQ_STRICT , state ) <nl> + . JumpIfTrue ( & ( generator_resume_points_ [ i ] ) ) ; <nl> + } <nl> + builder ( ) - > Illegal ( ) ; / / Should never get here . <nl> + } <nl> + <nl> + builder ( ) - > Bind ( & regular_call ) ; <nl> + / / This is a regular call . Fall through to the ordinary function prologue , <nl> + / / after which we will run into the generator object creation and the initial <nl> + / / yield ( both inserted by the parser ) . <nl> + } <nl> <nl> void BytecodeGenerator : : VisitBlock ( Block * stmt ) { <nl> / / Visit declarations and statements . <nl> void BytecodeGenerator : : VisitAssignment ( Assignment * expr ) { <nl> execution_result ( ) - > SetResultInAccumulator ( ) ; <nl> } <nl> <nl> + void BytecodeGenerator : : VisitYield ( Yield * expr ) { <nl> + int id = generator_yields_seen_ + + ; <nl> + <nl> + builder ( ) - > SetExpressionPosition ( expr ) ; <nl> + Register value = VisitForRegisterValue ( expr - > expression ( ) ) ; <nl> + <nl> + register_allocator ( ) - > PrepareForConsecutiveAllocations ( 2 ) ; <nl> + Register generator = register_allocator ( ) - > NextConsecutiveRegister ( ) ; <nl> + Register state = register_allocator ( ) - > NextConsecutiveRegister ( ) ; <nl> + <nl> + / / Save context , registers , and state . Then return . <nl> + VisitForRegisterValue ( expr - > generator_object ( ) , generator ) ; <nl> + builder ( ) <nl> + - > LoadLiteral ( Smi : : FromInt ( id ) ) <nl> + . StoreAccumulatorInRegister ( state ) <nl> + . CallRuntime ( Runtime : : kSuspendIgnitionGenerator , generator , 2 ) <nl> + . LoadAccumulatorWithRegister ( value ) <nl> + . Return ( ) ; / / Hard return ( ignore any finally blocks ) . <nl> + <nl> + builder ( ) - > Bind ( & ( generator_resume_points_ [ id ] ) ) ; <nl> + / / Upon resume , we continue here . <nl> + <nl> + { <nl> + RegisterAllocationScope register_scope ( this ) ; <nl> + <nl> + Register input = register_allocator ( ) - > NewRegister ( ) ; <nl> + builder ( ) <nl> + - > CallRuntime ( Runtime : : kGeneratorGetInput , generator , 1 ) <nl> + . StoreAccumulatorInRegister ( input ) ; <nl> + <nl> + Register resume_mode = register_allocator ( ) - > NewRegister ( ) ; <nl> + builder ( ) <nl> + - > CallRuntime ( Runtime : : kGeneratorGetResumeMode , generator , 1 ) <nl> + . StoreAccumulatorInRegister ( resume_mode ) ; <nl> + <nl> + / / Now dispatch on resume mode . <nl> + <nl> + BytecodeLabel resume_with_next ; <nl> + BytecodeLabel resume_with_return ; <nl> + BytecodeLabel resume_with_throw ; <nl> <nl> - void BytecodeGenerator : : VisitYield ( Yield * expr ) { UNIMPLEMENTED ( ) ; } <nl> + builder ( ) <nl> + - > LoadLiteral ( Smi : : FromInt ( JSGeneratorObject : : kNext ) ) <nl> + . CompareOperation ( Token : : EQ_STRICT , resume_mode ) <nl> + . JumpIfTrue ( & resume_with_next ) <nl> + . LoadLiteral ( Smi : : FromInt ( JSGeneratorObject : : kThrow ) ) <nl> + . CompareOperation ( Token : : EQ_STRICT , resume_mode ) <nl> + . JumpIfTrue ( & resume_with_throw ) <nl> + . Jump ( & resume_with_return ) ; <nl> + <nl> + builder ( ) - > Bind ( & resume_with_return ) ; <nl> + { <nl> + register_allocator ( ) - > PrepareForConsecutiveAllocations ( 2 ) ; <nl> + Register value = register_allocator ( ) - > NextConsecutiveRegister ( ) ; <nl> + Register done = register_allocator ( ) - > NextConsecutiveRegister ( ) ; <nl> + builder ( ) <nl> + - > MoveRegister ( input , value ) <nl> + . LoadTrue ( ) <nl> + . StoreAccumulatorInRegister ( done ) <nl> + . CallRuntime ( Runtime : : kCreateIterResultObject , value , 2 ) ; <nl> + execution_control ( ) - > ReturnAccumulator ( ) ; <nl> + } <nl> <nl> + builder ( ) - > Bind ( & resume_with_throw ) ; <nl> + builder ( ) <nl> + - > LoadAccumulatorWithRegister ( input ) <nl> + . Throw ( ) ; <nl> + <nl> + builder ( ) - > Bind ( & resume_with_next ) ; <nl> + builder ( ) - > LoadAccumulatorWithRegister ( input ) ; <nl> + } <nl> + execution_result ( ) - > SetResultInAccumulator ( ) ; <nl> + } <nl> <nl> void BytecodeGenerator : : VisitThrow ( Throw * expr ) { <nl> VisitForAccumulatorValue ( expr - > exception ( ) ) ; <nl> builder ( ) - > SetExpressionPosition ( expr ) ; <nl> builder ( ) - > Throw ( ) ; <nl> - / / Throw statments are modeled as expression instead of statments . These are <nl> - / / converted from assignment statements in Rewriter : : ReWrite pass . An <nl> + / / Throw statements are modeled as expressions instead of statements . These <nl> + / / are converted from assignment statements in Rewriter : : ReWrite pass . An <nl> / / assignment statement expects a value in the accumulator . This is a hack to <nl> / / avoid DCHECK fails assert accumulator has been set . <nl> execution_result ( ) - > SetResultInAccumulator ( ) ; <nl> mmm a / src / interpreter / bytecode - generator . h <nl> ppp b / src / interpreter / bytecode - generator . h <nl> class BytecodeGenerator final : public AstVisitor { <nl> void BuildHoleCheckForVariableLoad ( VariableMode mode , Handle < String > name ) ; <nl> void BuildHoleCheckForVariableAssignment ( Variable * variable , Token : : Value op ) ; <nl> <nl> + void VisitGeneratorPrologue ( ) ; <nl> + <nl> void VisitArgumentsObject ( Variable * variable ) ; <nl> void VisitRestArgumentsArray ( Variable * rest ) ; <nl> void VisitCallSuper ( Call * call ) ; <nl> class BytecodeGenerator final : public AstVisitor { <nl> ContextScope * execution_context_ ; <nl> ExpressionResultScope * execution_result_ ; <nl> RegisterAllocationScope * register_allocator_ ; <nl> + ZoneVector < BytecodeLabel > generator_resume_points_ ; <nl> int try_catch_nesting_level_ ; <nl> int try_finally_nesting_level_ ; <nl> + int generator_yields_seen_ ; <nl> } ; <nl> <nl> } / / namespace interpreter <nl> mmm a / src / interpreter / bytecode - register - allocator . h <nl> ppp b / src / interpreter / bytecode - register - allocator . h <nl> class TemporaryRegisterAllocator final { <nl> DISALLOW_COPY_AND_ASSIGN ( TemporaryRegisterAllocator ) ; <nl> } ; <nl> <nl> - / / A class than allows the instantiator to allocate temporary registers that are <nl> + / / A class that allows the instantiator to allocate temporary registers that are <nl> / / cleaned up when scope is closed . <nl> class BytecodeRegisterAllocator final { <nl> public : <nl> mmm a / src / isolate . cc <nl> ppp b / src / isolate . cc <nl> Object * Isolate : : UnwindAndFindHandler ( ) { <nl> / / position of the exception handler . The special builtin below will <nl> / / take care of continuing to dispatch at that position . Also restore <nl> / / the correct context for the handler from the interpreter register . <nl> - context = Context : : cast ( js_frame - > GetInterpreterRegister ( context_reg ) ) ; <nl> + context = Context : : cast ( js_frame - > ReadInterpreterRegister ( context_reg ) ) ; <nl> js_frame - > PatchBytecodeOffset ( static_cast < int > ( offset ) ) ; <nl> offset = 0 ; <nl> <nl> mmm a / src / mips / builtins - mips . cc <nl> ppp b / src / mips / builtins - mips . cc <nl> void Builtins : : Generate_ResumeGeneratorTrampoline ( MacroAssembler * masm ) { <nl> __ bind ( & done_loop ) ; <nl> } <nl> <nl> - / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> - / / the generator was suspended . <nl> - FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> - __ Push ( ra , fp ) ; <nl> - __ Move ( fp , sp ) ; <nl> - __ Push ( cp , t0 ) ; <nl> - <nl> - / / Restore the operand stack . <nl> - __ lw ( a0 , FieldMemOperand ( a1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> - __ lw ( a3 , FieldMemOperand ( a0 , FixedArray : : kLengthOffset ) ) ; <nl> - __ Addu ( a0 , a0 , Operand ( FixedArray : : kHeaderSize - kHeapObjectTag ) ) ; <nl> - __ Lsa ( a3 , a0 , a3 , kPointerSizeLog2 - 1 ) ; <nl> + / / Dispatch on the kind of generator object . <nl> + Label old_generator ; <nl> + __ lw ( a3 , FieldMemOperand ( t0 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ lw ( a3 , FieldMemOperand ( a3 , SharedFunctionInfo : : kFunctionDataOffset ) ) ; <nl> + __ GetObjectType ( a3 , a3 , a3 ) ; <nl> + __ Branch ( & old_generator , ne , a3 , Operand ( BYTECODE_ARRAY_TYPE ) ) ; <nl> + <nl> + / / New - style ( ignition / turbofan ) generator object . <nl> { <nl> - Label done_loop , loop ; <nl> - __ bind ( & loop ) ; <nl> - __ Branch ( & done_loop , eq , a0 , Operand ( a3 ) ) ; <nl> - __ lw ( t1 , MemOperand ( a0 ) ) ; <nl> - __ Push ( t1 ) ; <nl> - __ Branch ( USE_DELAY_SLOT , & loop ) ; <nl> - __ addiu ( a0 , a0 , kPointerSize ) ; / / In delay slot . <nl> - __ bind ( & done_loop ) ; <nl> + __ lw ( a0 , FieldMemOperand ( t0 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ lw ( a0 , <nl> + FieldMemOperand ( a0 , SharedFunctionInfo : : kFormalParameterCountOffset ) ) ; <nl> + __ SmiUntag ( a0 ) ; <nl> + / / We abuse new . target both to indicate that this is a resume call and to <nl> + / / pass in the generator object . In ordinary calls , new . target is always <nl> + / / undefined because generator functions are non - constructable . <nl> + __ Move ( a3 , a1 ) ; <nl> + __ Move ( a1 , t0 ) ; <nl> + __ lw ( a2 , FieldMemOperand ( a1 , JSFunction : : kCodeEntryOffset ) ) ; <nl> + __ Jump ( a2 ) ; <nl> } <nl> <nl> - / / Reset operand stack so we don ' t leak . <nl> - __ LoadRoot ( t1 , Heap : : kEmptyFixedArrayRootIndex ) ; <nl> - __ sw ( t1 , FieldMemOperand ( a1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + / / Old - style ( full - codegen ) generator object <nl> + __ bind ( & old_generator ) ; <nl> + { <nl> + / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> + / / the generator was suspended . <nl> + FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> + __ Push ( ra , fp ) ; <nl> + __ Move ( fp , sp ) ; <nl> + __ Push ( cp , t0 ) ; <nl> + <nl> + / / Restore the operand stack . <nl> + __ lw ( a0 , FieldMemOperand ( a1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + __ lw ( a3 , FieldMemOperand ( a0 , FixedArray : : kLengthOffset ) ) ; <nl> + __ Addu ( a0 , a0 , Operand ( FixedArray : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + __ Lsa ( a3 , a0 , a3 , kPointerSizeLog2 - 1 ) ; <nl> + { <nl> + Label done_loop , loop ; <nl> + __ bind ( & loop ) ; <nl> + __ Branch ( & done_loop , eq , a0 , Operand ( a3 ) ) ; <nl> + __ lw ( t1 , MemOperand ( a0 ) ) ; <nl> + __ Push ( t1 ) ; <nl> + __ Branch ( USE_DELAY_SLOT , & loop ) ; <nl> + __ addiu ( a0 , a0 , kPointerSize ) ; / / In delay slot . <nl> + __ bind ( & done_loop ) ; <nl> + } <nl> <nl> - / / Resume the generator function at the continuation . <nl> - __ lw ( a3 , FieldMemOperand ( t0 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> - __ lw ( a3 , FieldMemOperand ( a3 , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> - __ Addu ( a3 , a3 , Operand ( Code : : kHeaderSize - kHeapObjectTag ) ) ; <nl> - __ lw ( a2 , FieldMemOperand ( a1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> - __ SmiUntag ( a2 ) ; <nl> - __ Addu ( a3 , a3 , Operand ( a2 ) ) ; <nl> - __ li ( a2 , Operand ( Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ) ; <nl> - __ sw ( a2 , FieldMemOperand ( a1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> - __ Move ( v0 , a1 ) ; / / Continuation expects generator object in v0 . <nl> - __ Jump ( a3 ) ; <nl> + / / Reset operand stack so we don ' t leak . <nl> + __ LoadRoot ( t1 , Heap : : kEmptyFixedArrayRootIndex ) ; <nl> + __ sw ( t1 , FieldMemOperand ( a1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + <nl> + / / Resume the generator function at the continuation . <nl> + __ lw ( a3 , FieldMemOperand ( t0 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ lw ( a3 , FieldMemOperand ( a3 , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> + __ Addu ( a3 , a3 , Operand ( Code : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + __ lw ( a2 , FieldMemOperand ( a1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> + __ SmiUntag ( a2 ) ; <nl> + __ Addu ( a3 , a3 , Operand ( a2 ) ) ; <nl> + __ li ( a2 , Operand ( Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ) ; <nl> + __ sw ( a2 , FieldMemOperand ( a1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> + __ Move ( v0 , a1 ) ; / / Continuation expects generator object in v0 . <nl> + __ Jump ( a3 ) ; <nl> + } <nl> } <nl> <nl> / / Generate code for entering a JS function with the interpreter . <nl> mmm a / src / mips64 / builtins - mips64 . cc <nl> ppp b / src / mips64 / builtins - mips64 . cc <nl> void Builtins : : Generate_ResumeGeneratorTrampoline ( MacroAssembler * masm ) { <nl> __ bind ( & done_loop ) ; <nl> } <nl> <nl> - / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> - / / the generator was suspended . <nl> - FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> - __ Push ( ra , fp ) ; <nl> - __ Move ( fp , sp ) ; <nl> - __ Push ( cp , a4 ) ; <nl> - <nl> - / / Restore the operand stack . <nl> - __ ld ( a0 , FieldMemOperand ( a1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> - __ ld ( a3 , FieldMemOperand ( a0 , FixedArray : : kLengthOffset ) ) ; <nl> - __ SmiUntag ( a3 ) ; <nl> - __ Daddu ( a0 , a0 , Operand ( FixedArray : : kHeaderSize - kHeapObjectTag ) ) ; <nl> - __ Dlsa ( a3 , a0 , a3 , kPointerSizeLog2 ) ; <nl> + / / Dispatch on the kind of generator object . <nl> + Label old_generator ; <nl> + __ ld ( a3 , FieldMemOperand ( a4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ ld ( a3 , FieldMemOperand ( a3 , SharedFunctionInfo : : kFunctionDataOffset ) ) ; <nl> + __ GetObjectType ( a3 , a3 , a3 ) ; <nl> + __ Branch ( & old_generator , ne , a3 , Operand ( BYTECODE_ARRAY_TYPE ) ) ; <nl> + <nl> + / / New - style ( ignition / turbofan ) generator object . <nl> { <nl> - Label done_loop , loop ; <nl> - __ bind ( & loop ) ; <nl> - __ Branch ( & done_loop , eq , a0 , Operand ( a3 ) ) ; <nl> - __ ld ( a5 , MemOperand ( a0 ) ) ; <nl> - __ Push ( a5 ) ; <nl> - __ Branch ( USE_DELAY_SLOT , & loop ) ; <nl> - __ daddiu ( a0 , a0 , kPointerSize ) ; / / In delay slot . <nl> - __ bind ( & done_loop ) ; <nl> + __ ld ( a0 , FieldMemOperand ( a4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ lw ( a0 , <nl> + FieldMemOperand ( a0 , SharedFunctionInfo : : kFormalParameterCountOffset ) ) ; <nl> + __ SmiUntag ( a0 ) ; <nl> + / / We abuse new . target both to indicate that this is a resume call and to <nl> + / / pass in the generator object . In ordinary calls , new . target is always <nl> + / / undefined because generator functions are non - constructable . <nl> + __ Move ( a3 , a1 ) ; <nl> + __ Move ( a1 , a4 ) ; <nl> + __ ld ( a2 , FieldMemOperand ( a1 , JSFunction : : kCodeEntryOffset ) ) ; <nl> + __ Jump ( a2 ) ; <nl> } <nl> <nl> - / / Reset operand stack so we don ' t leak . <nl> - __ LoadRoot ( a5 , Heap : : kEmptyFixedArrayRootIndex ) ; <nl> - __ sd ( a5 , FieldMemOperand ( a1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + / / Old - style ( full - codegen ) generator object <nl> + __ bind ( & old_generator ) ; <nl> + { <nl> + / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> + / / the generator was suspended . <nl> + FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> + __ Push ( ra , fp ) ; <nl> + __ Move ( fp , sp ) ; <nl> + __ Push ( cp , a4 ) ; <nl> + <nl> + / / Restore the operand stack . <nl> + __ ld ( a0 , FieldMemOperand ( a1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + __ ld ( a3 , FieldMemOperand ( a0 , FixedArray : : kLengthOffset ) ) ; <nl> + __ SmiUntag ( a3 ) ; <nl> + __ Daddu ( a0 , a0 , Operand ( FixedArray : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + __ Dlsa ( a3 , a0 , a3 , kPointerSizeLog2 ) ; <nl> + { <nl> + Label done_loop , loop ; <nl> + __ bind ( & loop ) ; <nl> + __ Branch ( & done_loop , eq , a0 , Operand ( a3 ) ) ; <nl> + __ ld ( a5 , MemOperand ( a0 ) ) ; <nl> + __ Push ( a5 ) ; <nl> + __ Branch ( USE_DELAY_SLOT , & loop ) ; <nl> + __ daddiu ( a0 , a0 , kPointerSize ) ; / / In delay slot . <nl> + __ bind ( & done_loop ) ; <nl> + } <nl> <nl> - / / Resume the generator function at the continuation . <nl> - __ ld ( a3 , FieldMemOperand ( a4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> - __ ld ( a3 , FieldMemOperand ( a3 , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> - __ Daddu ( a3 , a3 , Operand ( Code : : kHeaderSize - kHeapObjectTag ) ) ; <nl> - __ ld ( a2 , FieldMemOperand ( a1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> - __ SmiUntag ( a2 ) ; <nl> - __ Daddu ( a3 , a3 , Operand ( a2 ) ) ; <nl> - __ li ( a2 , Operand ( Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ) ; <nl> - __ sd ( a2 , FieldMemOperand ( a1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> - __ Move ( v0 , a1 ) ; / / Continuation expects generator object in v0 . <nl> - __ Jump ( a3 ) ; <nl> + / / Reset operand stack so we don ' t leak . <nl> + __ LoadRoot ( a5 , Heap : : kEmptyFixedArrayRootIndex ) ; <nl> + __ sd ( a5 , FieldMemOperand ( a1 , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + <nl> + / / Resume the generator function at the continuation . <nl> + __ ld ( a3 , FieldMemOperand ( a4 , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ ld ( a3 , FieldMemOperand ( a3 , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> + __ Daddu ( a3 , a3 , Operand ( Code : : kHeaderSize - kHeapObjectTag ) ) ; <nl> + __ ld ( a2 , FieldMemOperand ( a1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> + __ SmiUntag ( a2 ) ; <nl> + __ Daddu ( a3 , a3 , Operand ( a2 ) ) ; <nl> + __ li ( a2 , Operand ( Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ) ; <nl> + __ sd ( a2 , FieldMemOperand ( a1 , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> + __ Move ( v0 , a1 ) ; / / Continuation expects generator object in v0 . <nl> + __ Jump ( a3 ) ; <nl> + } <nl> } <nl> <nl> void Builtins : : Generate_ConstructedNonConstructable ( MacroAssembler * masm ) { <nl> mmm a / src / objects - inl . h <nl> ppp b / src / objects - inl . h <nl> SMI_ACCESSORS ( JSGeneratorObject , continuation , kContinuationOffset ) <nl> ACCESSORS ( JSGeneratorObject , operand_stack , FixedArray , kOperandStackOffset ) <nl> <nl> bool JSGeneratorObject : : is_suspended ( ) { <nl> - DCHECK_LT ( kGeneratorExecuting , kGeneratorClosed ) ; <nl> - DCHECK_EQ ( kGeneratorClosed , 0 ) ; <nl> - return continuation ( ) > 0 ; <nl> + DCHECK_LT ( kGeneratorExecuting , 0 ) ; <nl> + DCHECK_LT ( kGeneratorClosed , 0 ) ; <nl> + return continuation ( ) > = 0 ; <nl> } <nl> <nl> bool JSGeneratorObject : : is_closed ( ) { <nl> mmm a / src / objects . h <nl> ppp b / src / objects . h <nl> class JSGeneratorObject : public JSObject { <nl> DECLARE_VERIFIER ( JSGeneratorObject ) <nl> <nl> / / Magic sentinel values for the continuation . <nl> - static const int kGeneratorExecuting = - 1 ; <nl> - static const int kGeneratorClosed = 0 ; <nl> + static const int kGeneratorExecuting = - 2 ; <nl> + static const int kGeneratorClosed = - 1 ; <nl> <nl> / / Layout description . <nl> static const int kFunctionOffset = JSObject : : kHeaderSize ; <nl> mmm a / src / runtime / runtime - generator . cc <nl> ppp b / src / runtime / runtime - generator . cc <nl> RUNTIME_FUNCTION ( Runtime_SuspendJSGeneratorObject ) { <nl> return isolate - > heap ( ) - > undefined_value ( ) ; <nl> } <nl> <nl> + <nl> RUNTIME_FUNCTION ( Runtime_GeneratorClose ) { <nl> HandleScope scope ( isolate ) ; <nl> DCHECK ( args . length ( ) = = 1 ) ; <nl> RUNTIME_FUNCTION ( Runtime_GeneratorGetInput ) { <nl> } <nl> <nl> <nl> + / / Returns resume mode of generator activation . <nl> + RUNTIME_FUNCTION ( Runtime_GeneratorGetResumeMode ) { <nl> + HandleScope scope ( isolate ) ; <nl> + DCHECK ( args . length ( ) = = 1 ) ; <nl> + CONVERT_ARG_HANDLE_CHECKED ( JSGeneratorObject , generator , 0 ) ; <nl> + <nl> + return Smi : : FromInt ( generator - > resume_mode ( ) ) ; <nl> + } <nl> + <nl> + <nl> / / Returns generator continuation as a PC offset , or the magic - 1 or 0 values . <nl> RUNTIME_FUNCTION ( Runtime_GeneratorGetContinuation ) { <nl> HandleScope scope ( isolate ) ; <nl> RUNTIME_FUNCTION ( Runtime_GeneratorGetSourcePosition ) { <nl> return isolate - > heap ( ) - > undefined_value ( ) ; <nl> } <nl> <nl> + <nl> + RUNTIME_FUNCTION ( Runtime_SuspendIgnitionGenerator ) { <nl> + HandleScope scope ( isolate ) ; <nl> + DCHECK ( args . length ( ) = = 2 ) ; <nl> + CONVERT_ARG_HANDLE_CHECKED ( JSGeneratorObject , generator , 0 ) ; <nl> + CONVERT_ARG_HANDLE_CHECKED ( Smi , state , 1 ) ; <nl> + <nl> + JavaScriptFrameIterator it ( isolate ) ; <nl> + JavaScriptFrame * frame = it . frame ( ) ; <nl> + Handle < JSFunction > function ( frame - > function ( ) ) ; <nl> + CHECK ( function - > shared ( ) - > is_generator ( ) ) ; <nl> + CHECK_EQ ( frame - > type ( ) , StackFrame : : INTERPRETED ) ; <nl> + <nl> + / / Save register file . <nl> + int size = function - > shared ( ) - > bytecode_array ( ) - > register_count ( ) ; <nl> + Handle < FixedArray > register_file = isolate - > factory ( ) - > NewFixedArray ( size ) ; <nl> + for ( int i = 0 ; i < size ; + + i ) { <nl> + Object * value = <nl> + static_cast < InterpretedFrame * > ( frame ) - > ReadInterpreterRegister ( i ) ; <nl> + register_file - > set ( i , value ) ; <nl> + } <nl> + <nl> + generator - > set_operand_stack ( * register_file ) ; <nl> + generator - > set_context ( Context : : cast ( frame - > context ( ) ) ) ; <nl> + generator - > set_continuation ( state - > value ( ) ) ; <nl> + <nl> + return isolate - > heap ( ) - > undefined_value ( ) ; <nl> + } <nl> + <nl> + <nl> + RUNTIME_FUNCTION ( Runtime_ResumeIgnitionGenerator ) { <nl> + HandleScope scope ( isolate ) ; <nl> + DCHECK ( args . length ( ) = = 1 ) ; <nl> + CONVERT_ARG_HANDLE_CHECKED ( JSGeneratorObject , generator , 0 ) ; <nl> + <nl> + JavaScriptFrameIterator it ( isolate ) ; <nl> + JavaScriptFrame * frame = it . frame ( ) ; <nl> + Handle < JSFunction > function ( frame - > function ( ) ) ; <nl> + CHECK ( function - > shared ( ) - > is_generator ( ) ) ; <nl> + CHECK_EQ ( frame - > type ( ) , StackFrame : : INTERPRETED ) ; <nl> + <nl> + / / Restore register file . <nl> + int size = function - > shared ( ) - > bytecode_array ( ) - > register_count ( ) ; <nl> + DCHECK_EQ ( size , generator - > operand_stack ( ) - > length ( ) ) ; <nl> + for ( int i = 0 ; i < size ; + + i ) { <nl> + Object * value = generator - > operand_stack ( ) - > get ( i ) ; <nl> + static_cast < InterpretedFrame * > ( frame ) - > WriteInterpreterRegister ( i , value ) ; <nl> + } <nl> + generator - > set_operand_stack ( isolate - > heap ( ) - > empty_fixed_array ( ) ) ; <nl> + <nl> + int state = generator - > continuation ( ) ; <nl> + generator - > set_continuation ( JSGeneratorObject : : kGeneratorExecuting ) ; <nl> + return Smi : : FromInt ( state ) ; <nl> + } <nl> + <nl> } / / namespace internal <nl> } / / namespace v8 <nl> mmm a / src / runtime / runtime . h <nl> ppp b / src / runtime / runtime . h <nl> namespace internal { <nl> F ( GeneratorGetReceiver , 1 , 1 ) \ <nl> F ( GeneratorGetInput , 1 , 1 ) \ <nl> F ( GeneratorGetContinuation , 1 , 1 ) \ <nl> - F ( GeneratorGetSourcePosition , 1 , 1 ) <nl> + F ( GeneratorGetSourcePosition , 1 , 1 ) \ <nl> + F ( GeneratorGetResumeMode , 1 , 1 ) \ <nl> + F ( SuspendIgnitionGenerator , 2 , 1 ) \ <nl> + F ( ResumeIgnitionGenerator , 1 , 1 ) <nl> <nl> # ifdef V8_I18N_SUPPORT <nl> # define FOR_EACH_INTRINSIC_I18N ( F ) \ <nl> mmm a / src / x64 / builtins - x64 . cc <nl> ppp b / src / x64 / builtins - x64 . cc <nl> void Builtins : : Generate_ResumeGeneratorTrampoline ( MacroAssembler * masm ) { <nl> __ bind ( & done_loop ) ; <nl> } <nl> <nl> - / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> - / / the generator was suspended . <nl> - FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> - __ PushReturnAddressFrom ( rax ) ; / / Return address . <nl> - __ Push ( rbp ) ; / / Caller ' s frame pointer . <nl> - __ Move ( rbp , rsp ) ; <nl> - __ Push ( rsi ) ; / / Callee ' s context . <nl> - __ Push ( rdi ) ; / / Callee ' s JS Function . <nl> + / / Dispatch on the kind of generator object . <nl> + Label old_generator ; <nl> + __ movp ( rcx , FieldOperand ( rdi , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ movp ( rcx , FieldOperand ( rcx , SharedFunctionInfo : : kFunctionDataOffset ) ) ; <nl> + __ CmpObjectType ( rcx , BYTECODE_ARRAY_TYPE , rcx ) ; <nl> + __ j ( not_equal , & old_generator ) ; <nl> <nl> - / / Restore the operand stack . <nl> - __ movp ( rsi , FieldOperand ( rbx , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> - __ SmiToInteger32 ( rax , FieldOperand ( rsi , FixedArray : : kLengthOffset ) ) ; <nl> + / / New - style ( ignition / turbofan ) generator object . <nl> { <nl> - Label done_loop , loop ; <nl> - __ Set ( rcx , 0 ) ; <nl> - __ bind ( & loop ) ; <nl> - __ cmpl ( rcx , rax ) ; <nl> - __ j ( equal , & done_loop , Label : : kNear ) ; <nl> - __ Push ( <nl> - FieldOperand ( rsi , rcx , times_pointer_size , FixedArray : : kHeaderSize ) ) ; <nl> - __ addl ( rcx , Immediate ( 1 ) ) ; <nl> - __ jmp ( & loop ) ; <nl> - __ bind ( & done_loop ) ; <nl> - } <nl> + __ PushReturnAddressFrom ( rax ) ; <nl> + __ movp ( rax , FieldOperand ( rdi , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ LoadSharedFunctionInfoSpecialField ( <nl> + rax , rax , SharedFunctionInfo : : kFormalParameterCountOffset ) ; <nl> + / / We abuse new . target both to indicate that this is a resume call and to <nl> + / / pass in the generator object . In ordinary calls , new . target is always <nl> + / / undefined because generator functions are non - constructable . <nl> + __ movp ( rdx , rbx ) ; <nl> + __ jmp ( FieldOperand ( rdi , JSFunction : : kCodeEntryOffset ) ) ; <nl> + } <nl> + <nl> + / / Old - style ( full - codegen ) generator object . <nl> + __ bind ( & old_generator ) ; <nl> + { <nl> + / / Enter a new JavaScript frame , and initialize its slots as they were when <nl> + / / the generator was suspended . <nl> + FrameScope scope ( masm , StackFrame : : MANUAL ) ; <nl> + __ PushReturnAddressFrom ( rax ) ; / / Return address . <nl> + __ Push ( rbp ) ; / / Caller ' s frame pointer . <nl> + __ Move ( rbp , rsp ) ; <nl> + __ Push ( rsi ) ; / / Callee ' s context . <nl> + __ Push ( rdi ) ; / / Callee ' s JS Function . <nl> + <nl> + / / Restore the operand stack . <nl> + __ movp ( rsi , FieldOperand ( rbx , JSGeneratorObject : : kOperandStackOffset ) ) ; <nl> + __ SmiToInteger32 ( rax , FieldOperand ( rsi , FixedArray : : kLengthOffset ) ) ; <nl> + { <nl> + Label done_loop , loop ; <nl> + __ Set ( rcx , 0 ) ; <nl> + __ bind ( & loop ) ; <nl> + __ cmpl ( rcx , rax ) ; <nl> + __ j ( equal , & done_loop , Label : : kNear ) ; <nl> + __ Push ( <nl> + FieldOperand ( rsi , rcx , times_pointer_size , FixedArray : : kHeaderSize ) ) ; <nl> + __ addl ( rcx , Immediate ( 1 ) ) ; <nl> + __ jmp ( & loop ) ; <nl> + __ bind ( & done_loop ) ; <nl> + } <nl> <nl> - / / Reset operand stack so we don ' t leak . <nl> - __ LoadRoot ( FieldOperand ( rbx , JSGeneratorObject : : kOperandStackOffset ) , <nl> - Heap : : kEmptyFixedArrayRootIndex ) ; <nl> + / / Reset operand stack so we don ' t leak . <nl> + __ LoadRoot ( FieldOperand ( rbx , JSGeneratorObject : : kOperandStackOffset ) , <nl> + Heap : : kEmptyFixedArrayRootIndex ) ; <nl> <nl> - / / Restore context . <nl> - __ movp ( rsi , FieldOperand ( rbx , JSGeneratorObject : : kContextOffset ) ) ; <nl> + / / Restore context . <nl> + __ movp ( rsi , FieldOperand ( rbx , JSGeneratorObject : : kContextOffset ) ) ; <nl> <nl> - / / Resume the generator function at the continuation . <nl> - __ movp ( rdx , FieldOperand ( rdi , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> - __ movp ( rdx , FieldOperand ( rdx , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> - __ SmiToInteger64 ( rcx , <nl> - FieldOperand ( rbx , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> - __ leap ( rdx , FieldOperand ( rdx , rcx , times_1 , Code : : kHeaderSize ) ) ; <nl> - __ Move ( FieldOperand ( rbx , JSGeneratorObject : : kContinuationOffset ) , <nl> - Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ; <nl> - __ movp ( rax , rbx ) ; / / Continuation expects generator object in rax . <nl> - __ jmp ( rdx ) ; <nl> + / / Resume the generator function at the continuation . <nl> + __ movp ( rdx , FieldOperand ( rdi , JSFunction : : kSharedFunctionInfoOffset ) ) ; <nl> + __ movp ( rdx , FieldOperand ( rdx , SharedFunctionInfo : : kCodeOffset ) ) ; <nl> + __ SmiToInteger64 ( <nl> + rcx , FieldOperand ( rbx , JSGeneratorObject : : kContinuationOffset ) ) ; <nl> + __ leap ( rdx , FieldOperand ( rdx , rcx , times_1 , Code : : kHeaderSize ) ) ; <nl> + __ Move ( FieldOperand ( rbx , JSGeneratorObject : : kContinuationOffset ) , <nl> + Smi : : FromInt ( JSGeneratorObject : : kGeneratorExecuting ) ) ; <nl> + __ movp ( rax , rbx ) ; / / Continuation expects generator object in rax . <nl> + __ jmp ( rdx ) ; <nl> + } <nl> } <nl> <nl> / / Generate code for entering a JS function with the interpreter . <nl> new file mode 100644 <nl> index 00000000000 . . 580cc98b725 <nl> mmm / dev / null <nl> ppp b / test / cctest / interpreter / bytecode_expectations / Generators . golden <nl> <nl> + # <nl> + # Autogenerated by generate - bytecode - expectations . <nl> + # <nl> + <nl> + mmm <nl> + pool type : mixed <nl> + execute : yes <nl> + wrap : no <nl> + test function name : f <nl> + ignition generators : yes <nl> + <nl> + mmm <nl> + snippet : " <nl> + function * f ( ) { } <nl> + " <nl> + frame size : 11 <nl> + parameter count : 1 <nl> + bytecode array length : 201 <nl> + bytecodes : [ <nl> + B ( Ldar ) , R ( new_target ) , <nl> + B ( JumpIfUndefined ) , U8 ( 15 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kResumeIgnitionGenerator ) , R ( new_target ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 1 ) , <nl> + B ( JumpIfTrue ) , U8 ( 54 ) , <nl> + B ( Illegal ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kNewFunctionContext ) , R ( closure ) , U8 ( 1 ) , <nl> + B ( PushContext ) , R ( 0 ) , <nl> + B ( Ldar ) , R ( this ) , <nl> + B ( StaContextSlot ) , R ( context ) , U8 ( 4 ) , <nl> + B ( StackCheck ) , <nl> + B ( Mov ) , R ( context ) , R ( 3 ) , <nl> + B ( Ldar ) , R ( closure ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 4 ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kCreateJSGeneratorObject ) , R ( 4 ) , U8 ( 2 ) , <nl> + B ( StaContextSlot ) , R ( context ) , U8 ( 5 ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 5 ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + B ( LdaZero ) , <nl> + B ( Star ) , R ( 6 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kSuspendIgnitionGenerator ) , R ( 5 ) , U8 ( 2 ) , <nl> + B ( Ldar ) , R ( 4 ) , <nl> + B ( Return ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorGetInput ) , R ( 5 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorGetResumeMode ) , R ( 5 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 8 ) , <nl> + B ( JumpIfTrue ) , U8 ( 31 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( TestEqualStrict ) , R ( 8 ) , <nl> + B ( JumpIfTrue ) , U8 ( 22 ) , <nl> + B ( Jump ) , U8 ( 2 ) , <nl> + B ( Mov ) , R ( 7 ) , R ( 9 ) , <nl> + B ( LdaTrue ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kCreateIterResultObject ) , R ( 9 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> + B ( LdaZero ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + B ( Jump ) , U8 ( 38 ) , <nl> + B ( Ldar ) , R ( 7 ) , <nl> + B ( Throw ) , <nl> + B ( Ldar ) , R ( 7 ) , <nl> + B ( LdaUndefined ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaTrue ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : k_CreateIterResultObject ) , R ( 4 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + B ( Jump ) , U8 ( 14 ) , <nl> + B ( LdaSmi ) , U8 ( - 1 ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + B ( Jump ) , U8 ( 8 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kInterpreterClearPendingMessage ) , R ( 0 ) , U8 ( 0 ) , <nl> + B ( Star ) , R ( 3 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 5 ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorClose ) , R ( 4 ) , U8 ( 1 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kInterpreterSetPendingMessage ) , R ( 3 ) , U8 ( 1 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 1 ) , <nl> + B ( JumpIfTrue ) , U8 ( 16 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( TestEqualStrict ) , R ( 1 ) , <nl> + B ( JumpIfTrue ) , U8 ( 13 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( TestEqualStrict ) , R ( 1 ) , <nl> + B ( JumpIfTrue ) , U8 ( 10 ) , <nl> + B ( Jump ) , U8 ( 11 ) , <nl> + B ( Ldar ) , R ( 2 ) , <nl> + B ( Return ) , <nl> + B ( Ldar ) , R ( 2 ) , <nl> + B ( Return ) , <nl> + B ( Ldar ) , R ( 2 ) , <nl> + B ( ReThrow ) , <nl> + B ( LdaUndefined ) , <nl> + B ( Return ) , <nl> + ] <nl> + constant pool : [ <nl> + ] <nl> + handlers : [ <nl> + [ 33 , 137 , 143 ] , <nl> + ] <nl> + <nl> + mmm <nl> + snippet : " <nl> + function * f ( ) { yield 42 } <nl> + " <nl> + frame size : 11 <nl> + parameter count : 1 <nl> + bytecode array length : 298 <nl> + bytecodes : [ <nl> + B ( Ldar ) , R ( new_target ) , <nl> + B ( JumpIfUndefined ) , U8 ( 21 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kResumeIgnitionGenerator ) , R ( new_target ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 1 ) , <nl> + B ( JumpIfTrue ) , U8 ( 60 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( TestEqualStrict ) , R ( 1 ) , <nl> + B ( JumpIfTrueConstant ) , U8 ( 0 ) , <nl> + B ( Illegal ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kNewFunctionContext ) , R ( closure ) , U8 ( 1 ) , <nl> + B ( PushContext ) , R ( 0 ) , <nl> + B ( Ldar ) , R ( this ) , <nl> + B ( StaContextSlot ) , R ( context ) , U8 ( 4 ) , <nl> + B ( StackCheck ) , <nl> + B ( Mov ) , R ( context ) , R ( 3 ) , <nl> + B ( Ldar ) , R ( closure ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 4 ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kCreateJSGeneratorObject ) , R ( 4 ) , U8 ( 2 ) , <nl> + B ( StaContextSlot ) , R ( context ) , U8 ( 5 ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 5 ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + B ( LdaZero ) , <nl> + B ( Star ) , R ( 6 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kSuspendIgnitionGenerator ) , R ( 5 ) , U8 ( 2 ) , <nl> + B ( Ldar ) , R ( 4 ) , <nl> + B ( Return ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorGetInput ) , R ( 5 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorGetResumeMode ) , R ( 5 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 8 ) , <nl> + B ( JumpIfTrue ) , U8 ( 31 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( TestEqualStrict ) , R ( 8 ) , <nl> + B ( JumpIfTrue ) , U8 ( 22 ) , <nl> + B ( Jump ) , U8 ( 2 ) , <nl> + B ( Mov ) , R ( 7 ) , R ( 9 ) , <nl> + B ( LdaTrue ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kCreateIterResultObject ) , R ( 9 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> + B ( LdaZero ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + B ( Jump ) , U8 ( 120 ) , <nl> + B ( Ldar ) , R ( 7 ) , <nl> + B ( Throw ) , <nl> + B ( Ldar ) , R ( 7 ) , <nl> + B ( LdaSmi ) , U8 ( 42 ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaFalse ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : k_CreateIterResultObject ) , R ( 4 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 5 ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kSuspendIgnitionGenerator ) , R ( 4 ) , U8 ( 2 ) , <nl> + B ( Ldar ) , R ( 6 ) , <nl> + B ( Return ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorGetInput ) , R ( 4 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorGetResumeMode ) , R ( 4 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 8 ) , <nl> + B ( JumpIfTrue ) , U8 ( 32 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( TestEqualStrict ) , R ( 8 ) , <nl> + B ( JumpIfTrue ) , U8 ( 23 ) , <nl> + B ( Jump ) , U8 ( 2 ) , <nl> + B ( Mov ) , R ( 7 ) , R ( 9 ) , <nl> + B ( LdaTrue ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kCreateIterResultObject ) , R ( 9 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + B ( Jump ) , U8 ( 38 ) , <nl> + B ( Ldar ) , R ( 7 ) , <nl> + B ( Throw ) , <nl> + B ( Ldar ) , R ( 7 ) , <nl> + B ( LdaUndefined ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaTrue ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : k_CreateIterResultObject ) , R ( 4 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + B ( Jump ) , U8 ( 14 ) , <nl> + B ( LdaSmi ) , U8 ( - 1 ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + B ( Jump ) , U8 ( 8 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> + B ( LdaSmi ) , U8 ( 3 ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kInterpreterClearPendingMessage ) , R ( 0 ) , U8 ( 0 ) , <nl> + B ( Star ) , R ( 3 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 5 ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorClose ) , R ( 4 ) , U8 ( 1 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kInterpreterSetPendingMessage ) , R ( 3 ) , U8 ( 1 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 1 ) , <nl> + B ( JumpIfTrue ) , U8 ( 22 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( TestEqualStrict ) , R ( 1 ) , <nl> + B ( JumpIfTrue ) , U8 ( 19 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( TestEqualStrict ) , R ( 1 ) , <nl> + B ( JumpIfTrue ) , U8 ( 16 ) , <nl> + B ( LdaSmi ) , U8 ( 3 ) , <nl> + B ( TestEqualStrict ) , R ( 1 ) , <nl> + B ( JumpIfTrue ) , U8 ( 13 ) , <nl> + B ( Jump ) , U8 ( 14 ) , <nl> + B ( Ldar ) , R ( 2 ) , <nl> + B ( Return ) , <nl> + B ( Ldar ) , R ( 2 ) , <nl> + B ( Return ) , <nl> + B ( Ldar ) , R ( 2 ) , <nl> + B ( Return ) , <nl> + B ( Ldar ) , R ( 2 ) , <nl> + B ( ReThrow ) , <nl> + B ( LdaUndefined ) , <nl> + B ( Return ) , <nl> + ] <nl> + constant pool : [ <nl> + kInstanceTypeDontCare , <nl> + ] <nl> + handlers : [ <nl> + [ 39 , 225 , 231 ] , <nl> + ] <nl> + <nl> + mmm <nl> + snippet : " <nl> + function * f ( ) { for ( let x of [ 42 ] ) yield x } <nl> + " <nl> + frame size : 17 <nl> + parameter count : 1 <nl> + bytecode array length : 786 <nl> + bytecodes : [ <nl> + B ( Ldar ) , R ( new_target ) , <nl> + B ( JumpIfUndefined ) , U8 ( 21 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kResumeIgnitionGenerator ) , R ( new_target ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 3 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 3 ) , <nl> + B ( JumpIfTrue ) , U8 ( 60 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( TestEqualStrict ) , R ( 3 ) , <nl> + B ( JumpIfTrueConstant ) , U8 ( 8 ) , <nl> + B ( Illegal ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kNewFunctionContext ) , R ( closure ) , U8 ( 1 ) , <nl> + B ( PushContext ) , R ( 0 ) , <nl> + B ( Ldar ) , R ( this ) , <nl> + B ( StaContextSlot ) , R ( context ) , U8 ( 4 ) , <nl> + B ( StackCheck ) , <nl> + B ( Mov ) , R ( context ) , R ( 5 ) , <nl> + B ( Ldar ) , R ( closure ) , <nl> + B ( Star ) , R ( 6 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 4 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kCreateJSGeneratorObject ) , R ( 6 ) , U8 ( 2 ) , <nl> + B ( StaContextSlot ) , R ( context ) , U8 ( 5 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 5 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> + B ( LdaZero ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kSuspendIgnitionGenerator ) , R ( 7 ) , U8 ( 2 ) , <nl> + B ( Ldar ) , R ( 6 ) , <nl> + B ( Return ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorGetInput ) , R ( 7 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorGetResumeMode ) , R ( 7 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 10 ) , <nl> + B ( JumpIfTrue ) , U8 ( 31 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( TestEqualStrict ) , R ( 10 ) , <nl> + B ( JumpIfTrue ) , U8 ( 22 ) , <nl> + B ( Jump ) , U8 ( 2 ) , <nl> + B ( Mov ) , R ( 9 ) , R ( 11 ) , <nl> + B ( LdaTrue ) , <nl> + B ( Star ) , R ( 12 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kCreateIterResultObject ) , R ( 11 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaZero ) , <nl> + B ( Star ) , R ( 3 ) , <nl> + B ( JumpConstant ) , U8 ( 16 ) , <nl> + B ( Ldar ) , R ( 9 ) , <nl> + B ( Throw ) , <nl> + B ( Ldar ) , R ( 9 ) , <nl> + B ( LdaConstant ) , U8 ( 0 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> + B ( Ldar ) , R ( closure ) , <nl> + B ( Star ) , R ( 7 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kPushBlockContext ) , R ( 6 ) , U8 ( 2 ) , <nl> + B ( PushContext ) , R ( 1 ) , <nl> + B ( LdaTheHole ) , <nl> + B ( StaContextSlot ) , R ( context ) , U8 ( 4 ) , <nl> + B ( LdaUndefined ) , <nl> + B ( StaContextSlot ) , R ( 1 ) , U8 ( 10 ) , <nl> + B ( LdaZero ) , <nl> + B ( StaContextSlot ) , R ( 1 ) , U8 ( 9 ) , <nl> + B ( Mov ) , R ( context ) , R ( 8 ) , <nl> + B ( Mov ) , R ( context ) , R ( 9 ) , <nl> + B ( CreateArrayLiteral ) , U8 ( 1 ) , U8 ( 0 ) , U8 ( 3 ) , <nl> + B ( Star ) , R ( 11 ) , <nl> + B ( LdaConstant ) , U8 ( 2 ) , <nl> + B ( KeyedLoadIC ) , R ( 11 ) , U8 ( 3 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( Call ) , R ( 10 ) , R ( 11 ) , U8 ( 1 ) , U8 ( 1 ) , <nl> + B ( StaContextSlot ) , R ( 1 ) , U8 ( 7 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 7 ) , <nl> + B ( Star ) , R ( 12 ) , <nl> + B ( LoadIC ) , R ( 12 ) , U8 ( 3 ) , U8 ( 7 ) , <nl> + B ( Star ) , R ( 11 ) , <nl> + B ( Call ) , R ( 11 ) , R ( 12 ) , U8 ( 1 ) , U8 ( 5 ) , <nl> + B ( StaContextSlot ) , R ( 1 ) , U8 ( 8 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( InvokeIntrinsic ) , U16 ( Runtime : : k_IsJSReceiver ) , R ( 10 ) , U8 ( 1 ) , <nl> + B ( LogicalNot ) , <nl> + B ( JumpIfFalse ) , U8 ( 12 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 8 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kThrowIteratorResultNotAnObject ) , R ( 10 ) , U8 ( 1 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 8 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( LoadIC ) , R ( 10 ) , U8 ( 4 ) , U8 ( 9 ) , <nl> + B ( JumpIfToBooleanTrueConstant ) , U8 ( 9 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( StaContextSlot ) , R ( 1 ) , U8 ( 9 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 8 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( LoadIC ) , R ( 10 ) , U8 ( 5 ) , U8 ( 11 ) , <nl> + B ( StaContextSlot ) , R ( 1 ) , U8 ( 6 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 10 ) , <nl> + B ( StackCheck ) , <nl> + B ( LdaConstant ) , U8 ( 6 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( Ldar ) , R ( closure ) , <nl> + B ( Star ) , R ( 11 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kPushBlockContext ) , R ( 10 ) , U8 ( 2 ) , <nl> + B ( PushContext ) , R ( 2 ) , <nl> + B ( LdaTheHole ) , <nl> + B ( StaContextSlot ) , R ( context ) , U8 ( 4 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 6 ) , <nl> + B ( StaContextSlot ) , R ( context ) , U8 ( 4 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 4 ) , <nl> + B ( JumpIfNotHole ) , U8 ( 11 ) , <nl> + B ( LdaConstant ) , U8 ( 7 ) , <nl> + B ( Star ) , R ( 11 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kThrowReferenceError ) , R ( 11 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( LdaFalse ) , <nl> + B ( Star ) , R ( 11 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : k_CreateIterResultObject ) , R ( 10 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 12 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 5 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 11 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kSuspendIgnitionGenerator ) , R ( 10 ) , U8 ( 2 ) , <nl> + B ( Ldar ) , R ( 12 ) , <nl> + B ( Return ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorGetInput ) , R ( 10 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 13 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorGetResumeMode ) , R ( 10 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 14 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 14 ) , <nl> + B ( JumpIfTrue ) , U8 ( 45 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( TestEqualStrict ) , R ( 14 ) , <nl> + B ( JumpIfTrue ) , U8 ( 36 ) , <nl> + B ( Jump ) , U8 ( 2 ) , <nl> + B ( Mov ) , R ( 13 ) , R ( 15 ) , <nl> + B ( LdaTrue ) , <nl> + B ( Star ) , R ( 16 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kCreateIterResultObject ) , R ( 15 ) , U8 ( 2 ) , <nl> + B ( PopContext ) , R ( 2 ) , <nl> + B ( PopContext ) , R ( 2 ) , <nl> + B ( PopContext ) , R ( 2 ) , <nl> + B ( PopContext ) , R ( 2 ) , <nl> + B ( PopContext ) , R ( 2 ) , <nl> + B ( PopContext ) , R ( 2 ) , <nl> + B ( PopContext ) , R ( 2 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> + B ( LdaZero ) , <nl> + B ( Star ) , R ( 6 ) , <nl> + B ( Jump ) , U8 ( 78 ) , <nl> + B ( Ldar ) , R ( 13 ) , <nl> + B ( Throw ) , <nl> + B ( Ldar ) , R ( 13 ) , <nl> + B ( PopContext ) , R ( 2 ) , <nl> + B ( LdaZero ) , <nl> + B ( StaContextSlot ) , R ( 1 ) , U8 ( 9 ) , <nl> + B ( Wide ) , B ( Jump ) , U16 ( - 210 ) , <nl> + B ( Jump ) , U8 ( 49 ) , <nl> + B ( Star ) , R ( 11 ) , <nl> + B ( LdaConstant ) , U8 ( 10 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( Ldar ) , R ( closure ) , <nl> + B ( Star ) , R ( 12 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kPushCatchContext ) , R ( 10 ) , U8 ( 3 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( PushContext ) , R ( 2 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 9 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( TestEqualStrict ) , R ( 10 ) , <nl> + B ( JumpIfFalse ) , U8 ( 7 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( StaContextSlot ) , R ( 1 ) , U8 ( 9 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 4 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kReThrow ) , R ( 10 ) , U8 ( 1 ) , <nl> + B ( PopContext ) , R ( 2 ) , <nl> + B ( LdaSmi ) , U8 ( - 1 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> + B ( Jump ) , U8 ( 8 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kInterpreterClearPendingMessage ) , R ( 0 ) , U8 ( 0 ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 9 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 9 ) , <nl> + B ( JumpIfTrue ) , U8 ( 10 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 7 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( LdaUndefined ) , <nl> + B ( TestEqualStrict ) , R ( 9 ) , <nl> + B ( LogicalNot ) , <nl> + B ( JumpIfFalseConstant ) , U8 ( 15 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 7 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( LoadIC ) , R ( 9 ) , U8 ( 11 ) , U8 ( 13 ) , <nl> + B ( StaContextSlot ) , R ( 1 ) , U8 ( 11 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 11 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( LdaNull ) , <nl> + B ( TestEqual ) , R ( 9 ) , <nl> + B ( JumpIfFalse ) , U8 ( 4 ) , <nl> + B ( JumpConstant ) , U8 ( 14 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 9 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( TestEqualStrict ) , R ( 9 ) , <nl> + B ( JumpIfFalse ) , U8 ( 82 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 11 ) , <nl> + B ( TypeOf ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( LdaConstant ) , U8 ( 12 ) , <nl> + B ( TestEqualStrict ) , R ( 9 ) , <nl> + B ( JumpIfFalse ) , U8 ( 4 ) , <nl> + B ( Jump ) , U8 ( 18 ) , <nl> + B ( Wide ) , B ( LdaSmi ) , U16 ( 139 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( LdaConstant ) , U8 ( 13 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kNewTypeError ) , R ( 9 ) , U8 ( 2 ) , <nl> + B ( Throw ) , <nl> + B ( Mov ) , R ( context ) , R ( 9 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 11 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 7 ) , <nl> + B ( Star ) , R ( 11 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : k_Call ) , R ( 10 ) , U8 ( 2 ) , <nl> + B ( Jump ) , U8 ( 30 ) , <nl> + B ( Star ) , R ( 11 ) , <nl> + B ( LdaConstant ) , U8 ( 10 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( Ldar ) , R ( closure ) , <nl> + B ( Star ) , R ( 12 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kPushCatchContext ) , R ( 10 ) , U8 ( 3 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kInterpreterClearPendingMessage ) , R ( 0 ) , U8 ( 0 ) , <nl> + B ( Ldar ) , R ( 9 ) , <nl> + B ( PushContext ) , R ( 2 ) , <nl> + B ( PopContext ) , R ( 2 ) , <nl> + B ( Jump ) , U8 ( 44 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 11 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 7 ) , <nl> + B ( Star ) , R ( 10 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : k_Call ) , R ( 9 ) , U8 ( 2 ) , <nl> + B ( StaContextSlot ) , R ( 1 ) , U8 ( 12 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 12 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( InvokeIntrinsic ) , U16 ( Runtime : : k_IsJSReceiver ) , R ( 9 ) , U8 ( 1 ) , <nl> + B ( JumpIfToBooleanFalse ) , U8 ( 4 ) , <nl> + B ( Jump ) , U8 ( 12 ) , <nl> + B ( LdaContextSlot ) , R ( 1 ) , U8 ( 12 ) , <nl> + B ( Star ) , R ( 9 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kThrowIteratorResultNotAnObject ) , R ( 9 ) , U8 ( 1 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kInterpreterSetPendingMessage ) , R ( 8 ) , U8 ( 1 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 6 ) , <nl> + B ( JumpIfTrue ) , U8 ( 10 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( TestEqualStrict ) , R ( 6 ) , <nl> + B ( JumpIfTrue ) , U8 ( 18 ) , <nl> + B ( Jump ) , U8 ( 30 ) , <nl> + B ( Ldar ) , R ( 7 ) , <nl> + B ( PopContext ) , R ( 1 ) , <nl> + B ( PopContext ) , R ( 1 ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 3 ) , <nl> + B ( Jump ) , U8 ( 49 ) , <nl> + B ( Ldar ) , R ( 7 ) , <nl> + B ( PopContext ) , R ( 1 ) , <nl> + B ( PopContext ) , R ( 1 ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 3 ) , <nl> + B ( Jump ) , U8 ( 35 ) , <nl> + B ( PopContext ) , R ( 1 ) , <nl> + B ( LdaUndefined ) , <nl> + B ( Star ) , R ( 6 ) , <nl> + B ( LdaTrue ) , <nl> + B ( Star ) , R ( 7 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : k_CreateIterResultObject ) , R ( 6 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaSmi ) , U8 ( 3 ) , <nl> + B ( Star ) , R ( 3 ) , <nl> + B ( Jump ) , U8 ( 14 ) , <nl> + B ( LdaSmi ) , U8 ( - 1 ) , <nl> + B ( Star ) , R ( 3 ) , <nl> + B ( Jump ) , U8 ( 8 ) , <nl> + B ( Star ) , R ( 4 ) , <nl> + B ( LdaSmi ) , U8 ( 4 ) , <nl> + B ( Star ) , R ( 3 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kInterpreterClearPendingMessage ) , R ( 0 ) , U8 ( 0 ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + B ( LdaContextSlot ) , R ( context ) , U8 ( 5 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kGeneratorClose ) , R ( 6 ) , U8 ( 1 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kInterpreterSetPendingMessage ) , R ( 5 ) , U8 ( 1 ) , <nl> + B ( LdaZero ) , <nl> + B ( TestEqualStrict ) , R ( 3 ) , <nl> + B ( JumpIfTrue ) , U8 ( 28 ) , <nl> + B ( LdaSmi ) , U8 ( 1 ) , <nl> + B ( TestEqualStrict ) , R ( 3 ) , <nl> + B ( JumpIfTrue ) , U8 ( 25 ) , <nl> + B ( LdaSmi ) , U8 ( 2 ) , <nl> + B ( TestEqualStrict ) , R ( 3 ) , <nl> + B ( JumpIfTrue ) , U8 ( 22 ) , <nl> + B ( LdaSmi ) , U8 ( 3 ) , <nl> + B ( TestEqualStrict ) , R ( 3 ) , <nl> + B ( JumpIfTrue ) , U8 ( 19 ) , <nl> + B ( LdaSmi ) , U8 ( 4 ) , <nl> + B ( TestEqualStrict ) , R ( 3 ) , <nl> + B ( JumpIfTrue ) , U8 ( 16 ) , <nl> + B ( Jump ) , U8 ( 17 ) , <nl> + B ( Ldar ) , R ( 4 ) , <nl> + B ( Return ) , <nl> + B ( Ldar ) , R ( 4 ) , <nl> + B ( Return ) , <nl> + B ( Ldar ) , R ( 4 ) , <nl> + B ( ReThrow ) , <nl> + B ( Ldar ) , R ( 4 ) , <nl> + B ( Return ) , <nl> + B ( Ldar ) , R ( 4 ) , <nl> + B ( ReThrow ) , <nl> + B ( LdaUndefined ) , <nl> + B ( Return ) , <nl> + ] <nl> + constant pool : [ <nl> + InstanceType : : FIXED_ARRAY_TYPE , <nl> + InstanceType : : FIXED_ARRAY_TYPE , <nl> + InstanceType : : SYMBOL_TYPE , <nl> + InstanceType : : ONE_BYTE_INTERNALIZED_STRING_TYPE , <nl> + InstanceType : : ONE_BYTE_INTERNALIZED_STRING_TYPE , <nl> + InstanceType : : ONE_BYTE_INTERNALIZED_STRING_TYPE , <nl> + InstanceType : : FIXED_ARRAY_TYPE , <nl> + InstanceType : : ONE_BYTE_INTERNALIZED_STRING_TYPE , <nl> + kInstanceTypeDontCare , <nl> + kInstanceTypeDontCare , <nl> + InstanceType : : ONE_BYTE_INTERNALIZED_STRING_TYPE , <nl> + InstanceType : : ONE_BYTE_INTERNALIZED_STRING_TYPE , <nl> + InstanceType : : ONE_BYTE_INTERNALIZED_STRING_TYPE , <nl> + InstanceType : : ONE_BYTE_INTERNALIZED_STRING_TYPE , <nl> + kInstanceTypeDontCare , <nl> + kInstanceTypeDontCare , <nl> + kInstanceTypeDontCare , <nl> + ] <nl> + handlers : [ <nl> + [ 39 , 704 , 710 ] , <nl> + [ 154 , 440 , 446 ] , <nl> + [ 157 , 391 , 393 ] , <nl> + [ 548 , 563 , 565 ] , <nl> + ] <nl> + <nl> mmm a / test / cctest / interpreter / generate - bytecode - expectations . cc <nl> ppp b / test / cctest / interpreter / generate - bytecode - expectations . cc <nl> class ProgramOptions final { <nl> execute_ ( true ) , <nl> top_level_ ( false ) , <nl> do_expressions_ ( false ) , <nl> + ignition_generators_ ( false ) , <nl> verbose_ ( false ) , <nl> const_pool_type_ ( <nl> BytecodeExpectationsPrinter : : ConstantPoolType : : kMixed ) { } <nl> class ProgramOptions final { <nl> bool execute ( ) const { return execute_ ; } <nl> bool top_level ( ) const { return top_level_ ; } <nl> bool do_expressions ( ) const { return do_expressions_ ; } <nl> + bool ignition_generators ( ) const { return ignition_generators_ ; } <nl> bool verbose ( ) const { return verbose_ ; } <nl> bool suppress_runtime_errors ( ) const { return rebaseline_ & & ! verbose_ ; } <nl> BytecodeExpectationsPrinter : : ConstantPoolType const_pool_type ( ) const { <nl> class ProgramOptions final { <nl> bool execute_ ; <nl> bool top_level_ ; <nl> bool do_expressions_ ; <nl> + bool ignition_generators_ ; <nl> bool verbose_ ; <nl> BytecodeExpectationsPrinter : : ConstantPoolType const_pool_type_ ; <nl> std : : vector < std : : string > input_filenames_ ; <nl> ProgramOptions ProgramOptions : : FromCommandLine ( int argc , char * * argv ) { <nl> options . top_level_ = true ; <nl> } else if ( strcmp ( argv [ i ] , " - - do - expressions " ) = = 0 ) { <nl> options . do_expressions_ = true ; <nl> + } else if ( strcmp ( argv [ i ] , " - - ignition - generators " ) = = 0 ) { <nl> + options . ignition_generators_ = true ; <nl> } else if ( strcmp ( argv [ i ] , " - - verbose " ) = = 0 ) { <nl> options . verbose_ = true ; <nl> } else if ( strncmp ( argv [ i ] , " - - output = " , 9 ) = = 0 ) { <nl> void ProgramOptions : : UpdateFromHeader ( std : : istream & stream ) { <nl> top_level_ = ParseBoolean ( line . c_str ( ) + 11 ) ; <nl> } else if ( line . compare ( 0 , 16 , " do expressions : " ) = = 0 ) { <nl> do_expressions_ = ParseBoolean ( line . c_str ( ) + 16 ) ; <nl> + } else if ( line . compare ( 0 , 21 , " ignition generators : " ) = = 0 ) { <nl> + do_expressions_ = ParseBoolean ( line . c_str ( ) + 21 ) ; <nl> } else if ( line = = " mmm " ) { <nl> break ; <nl> } else if ( line . empty ( ) ) { <nl> void ProgramOptions : : PrintHeader ( std : : ostream & stream ) const { / / NOLINT <nl> <nl> if ( top_level_ ) stream < < " \ ntop level : yes " ; <nl> if ( do_expressions_ ) stream < < " \ ndo expressions : yes " ; <nl> + if ( ignition_generators_ ) stream < < " \ nignition generators : yes " ; <nl> <nl> stream < < " \ n \ n " ; <nl> } <nl> void GenerateExpectationsFile ( std : : ostream & stream , / / NOLINT <nl> } <nl> <nl> if ( options . do_expressions ( ) ) i : : FLAG_harmony_do_expressions = true ; <nl> + if ( options . ignition_generators ( ) ) i : : FLAG_ignition_generators = true ; <nl> <nl> stream < < " # \ n # Autogenerated by generate - bytecode - expectations . \ n # \ n \ n " ; <nl> options . PrintHeader ( stream ) ; <nl> void PrintUsage ( const char * exec_path ) { <nl> " Specify the name of the test function . \ n " <nl> " - - top - level Process top level code , not the top - level function . \ n " <nl> " - - do - expressions Enable harmony_do_expressions flag . \ n " <nl> + " - - ignition - generators Enable ignition_generators flag . \ n " <nl> " - - output = file . name \ n " <nl> " Specify the output file . If not specified , output goes to " <nl> " stdout . \ n " <nl> mmm a / test / cctest / interpreter / test - bytecode - generator . cc <nl> ppp b / test / cctest / interpreter / test - bytecode - generator . cc <nl> TEST ( ClassAndSuperClass ) { <nl> LoadGolden ( " ClassAndSuperClass . golden " ) ) ; <nl> } <nl> <nl> + TEST ( Generators ) { <nl> + bool old_flag = FLAG_ignition_generators ; <nl> + FLAG_ignition_generators = true ; <nl> + <nl> + InitializedIgnitionHandleScope scope ; <nl> + BytecodeExpectationsPrinter printer ( CcTest : : isolate ( ) , <nl> + ConstantPoolType : : kMixed ) ; <nl> + printer . set_wrap ( false ) ; <nl> + printer . set_test_function_name ( " f " ) ; <nl> + <nl> + const char * snippets [ ] = { <nl> + " function * f ( ) { } " , <nl> + <nl> + " function * f ( ) { yield 42 } " , <nl> + <nl> + " function * f ( ) { for ( let x of [ 42 ] ) yield x } " , <nl> + } ; <nl> + <nl> + CHECK_EQ ( BuildActual ( printer , snippets ) , LoadGolden ( " Generators . golden " ) ) ; <nl> + <nl> + FLAG_ignition_generators = old_flag ; <nl> + } <nl> + <nl> } / / namespace interpreter <nl> } / / namespace internal <nl> } / / namespace v8 <nl> mmm a / test / cctest / interpreter / test - interpreter . cc <nl> ppp b / test / cctest / interpreter / test - interpreter . cc <nl> TEST ( InterpreterIllegalConstDeclaration ) { <nl> } <nl> } <nl> <nl> + TEST ( InterpreterGenerators ) { <nl> + bool old_flag = FLAG_ignition_generators ; <nl> + FLAG_ignition_generators = true ; <nl> + <nl> + HandleAndZoneScope handles ; <nl> + i : : Isolate * isolate = handles . main_isolate ( ) ; <nl> + i : : Factory * factory = isolate - > factory ( ) ; <nl> + <nl> + std : : pair < const char * , Handle < Object > > tests [ ] = { <nl> + { " function * f ( ) { } ; return f ( ) . next ( ) . value " , <nl> + factory - > undefined_value ( ) } , <nl> + { " function * f ( ) { yield 42 } ; return f ( ) . next ( ) . value " , <nl> + factory - > NewNumberFromInt ( 42 ) } , <nl> + { " function * f ( ) { for ( let x of [ 42 ] ) yield x } ; return f ( ) . next ( ) . value " , <nl> + factory - > NewNumberFromInt ( 42 ) } , <nl> + } ; <nl> + <nl> + for ( size_t i = 0 ; i < arraysize ( tests ) ; i + + ) { <nl> + std : : string source ( <nl> + InterpreterTester : : SourceForBody ( tests [ i ] . first ) ) ; <nl> + InterpreterTester tester ( handles . main_isolate ( ) , source . c_str ( ) ) ; <nl> + auto callable = tester . GetCallable < > ( ) ; <nl> + <nl> + Handle < i : : Object > return_value = callable ( ) . ToHandleChecked ( ) ; <nl> + CHECK ( return_value - > SameValue ( * tests [ i ] . second ) ) ; <nl> + } <nl> + <nl> + FLAG_ignition_generators = old_flag ; <nl> + } <nl> + <nl> + <nl> } / / namespace interpreter <nl> } / / namespace internal <nl> } / / namespace v8 <nl> mmm a / test / mjsunit / harmony / generators . js <nl> ppp b / test / mjsunit / harmony / generators . js <nl> <nl> / / Use of this source code is governed by a BSD - style license that can be <nl> / / found in the LICENSE file . <nl> <nl> + / / Flags : - - ignition - generators - - harmony - do - expressions <nl> + <nl> <nl> { / / yield in try - catch <nl> <nl> <nl> assertEquals ( { value : 42 , done : true } , x . return ( 42 ) ) ; <nl> } <nl> } <nl> + <nl> + <nl> + / / More or less random tests from here on . <nl> + <nl> + <nl> + { <nl> + function * foo ( ) { } <nl> + let g = foo ( ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( ) { return new . target } <nl> + let g = foo ( ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( ) { throw 666 ; return 42 } <nl> + let g = foo ( ) ; <nl> + assertThrowsEquals ( ( ) = > g . next ( ) , 666 ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( a ) { return a ; } <nl> + let g = foo ( 42 ) ; <nl> + assertEquals ( { value : 42 , done : true } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( a ) { a . iwashere = true ; return a ; } <nl> + let x = { } ; <nl> + let g = foo ( x ) ; <nl> + assertEquals ( { value : { iwashere : true } , done : true } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + let a = 42 ; <nl> + function * foo ( ) { return a ; } <nl> + let g = foo ( ) ; <nl> + assertEquals ( { value : 42 , done : true } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + let a = 40 ; <nl> + function * foo ( b ) { return a + b ; } <nl> + let g = foo ( 2 ) ; <nl> + assertEquals ( { value : 42 , done : true } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + let a = 40 ; <nl> + function * foo ( b ) { a - - ; b + + ; return a + b ; } <nl> + let g = foo ( 2 ) ; <nl> + assertEquals ( { value : 42 , done : true } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + let g ; <nl> + function * foo ( ) { g . next ( ) } <nl> + g = foo ( ) ; <nl> + assertThrows ( ( ) = > g . next ( ) , TypeError ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( ) { yield 2 ; yield 3 ; yield 4 } <nl> + g = foo ( ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 3 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 4 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( ) { yield 2 ; if ( true ) { yield 3 } ; yield 4 } <nl> + g = foo ( ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 3 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 4 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( ) { yield 2 ; if ( true ) { yield 3 ; yield 4 } } <nl> + g = foo ( ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 3 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 4 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( ) { yield 2 ; if ( false ) { yield 3 } ; yield 4 } <nl> + g = foo ( ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 4 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( ) { yield 2 ; while ( true ) { yield 3 } ; yield 4 } <nl> + g = foo ( ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 3 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 3 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 3 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 3 , done : false } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( ) { yield 2 ; ( yield 3 ) + 42 ; yield 4 } <nl> + g = foo ( ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 3 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 4 , done : false } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( ) { yield 2 ; ( do { yield 3 } ) + 42 ; yield 4 } <nl> + g = foo ( ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 3 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 4 , done : false } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( ) { yield 2 ; return ( yield 3 ) + 42 ; yield 4 } <nl> + g = foo ( ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 3 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 42 , done : true } , g . next ( 0 ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + let x = 42 ; <nl> + function * foo ( ) { <nl> + yield x ; <nl> + for ( let x in { a : 1 , b : 2 } ) { <nl> + let i = 2 ; <nl> + yield x ; <nl> + yield i ; <nl> + do { <nl> + yield i ; <nl> + } while ( i - - > 0 ) ; <nl> + } <nl> + yield x ; <nl> + return 5 ; <nl> + } <nl> + g = foo ( ) ; <nl> + assertEquals ( { value : 42 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : ' a ' , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 1 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 0 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : ' b ' , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 1 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 0 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 42 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 5 , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + let a = 3 ; <nl> + function * foo ( ) { <nl> + let b = 4 ; <nl> + yield 1 ; <nl> + { let c = 5 ; yield 2 ; yield a ; yield b ; yield c ; } <nl> + } <nl> + g = foo ( ) ; <nl> + assertEquals ( { value : 1 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 2 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 3 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 4 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : 5 , done : false } , g . next ( ) ) ; <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl> + <nl> + { <nl> + function * foo ( ) { <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + yield 42 ; <nl> + } <nl> + g = foo ( ) ; <nl> + for ( let i = 0 ; i < 100 ; + + i ) { <nl> + assertEquals ( { value : 42 , done : false } , g . next ( ) ) ; <nl> + } <nl> + assertEquals ( { value : undefined , done : true } , g . next ( ) ) ; <nl> + } <nl>
First version of the new generators implementation .
v8/v8
d0ccddd0324aa9391e76b611481bdc47f0f073de
2016-04-18T14:13:30Z
mmm a / js / common / tests / shell / shell - document - babies - noncluster . js <nl> ppp b / js / common / tests / shell / shell - document - babies - noncluster . js <nl> function CollectionDocumentSuiteReturnStuff ( ) { <nl> / / / @ brief executes the test suites <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - jsunity . run ( CollectionDocumentSuiteBabies ) ; <nl> + / / TODO FIXME : reactivate this test ! <nl> + / / jsunity . run ( CollectionDocumentSuiteBabies ) ; <nl> jsunity . run ( CollectionDocumentSuiteReturnStuff ) ; <nl> <nl> return jsunity . done ( ) ; <nl>
deactivate babies tests temporarily
arangodb/arangodb
f94f298862ee15351b2f903ad2fbcd9b21bcfd4d
2016-04-08T21:50:02Z
mmm a / src / clustering / administration / cli / admin_cluster_link . cc <nl> ppp b / src / clustering / administration / cli / admin_cluster_link . cc <nl> void admin_cluster_link_t : : do_admin_set_replicas_internal ( const namespace_id_t & <nl> } <nl> <nl> ns . replica_affinities . get_mutable ( ) [ dc_id ] = num_replicas - ( is_primary ? 1 : 0 ) ; <nl> + if ( ns . replica_affinities . get_mutable ( ) [ dc_id ] = = 0 ) { <nl> + ns . replica_affinities . get_mutable ( ) . erase ( dc_id ) ; <nl> + } <nl> ns . replica_affinities . upgrade_version ( change_request_id ) ; <nl> } <nl> <nl> mmm a / src / clustering / administration / issues / unsatisfiable_goals . cc <nl> ppp b / src / clustering / administration / issues / unsatisfiable_goals . cc <nl> static bool is_satisfiable ( <nl> for ( std : : map < datacenter_id_t , int > : : iterator it = machines_needed_in_dc . begin ( ) ; <nl> it ! = machines_needed_in_dc . end ( ) ; <nl> + + it ) { <nl> - if ( it - > first = = nil_uuid ( ) ) { <nl> + if ( it - > first = = nil_uuid ( ) | | it - > second = = 0 ) { <nl> continue ; <nl> } <nl> if ( ! std_contains ( unused_machines_in_dc , it - > first ) | | unused_machines_in_dc [ it - > first ] < it - > second ) { <nl>
fixing unsatisfiable goals not handling a replica affinity of 0 correctly , as well as the admin cli leaving around replica affinities of 0
rethinkdb/rethinkdb
f4cb07575a5b9028fc48d0c026909d68676d1bb5
2012-10-04T19:35:30Z
mmm a / src / clustering / immediate_consistency / backfill_metadata . cc <nl> ppp b / src / clustering / immediate_consistency / backfill_metadata . cc <nl> <nl> / / Copyright 2010 - 2015 RethinkDB , all rights reserved . <nl> # include " clustering / immediate_consistency / backfill_metadata . hpp " <nl> <nl> + backfill_config_t : : backfill_config_t ( ) : <nl> + item_queue_mem_size ( 4 * MEGABYTE ) , <nl> + item_chunk_mem_size ( 100 * KILOBYTE ) , <nl> + pre_item_queue_mem_size ( 4 * MEGABYTE ) , <nl> + pre_item_chunk_mem_size ( 100 * KILOBYTE ) , <nl> + write_queue_count ( 1000 ) , <nl> + write_queue_trickle_fraction ( 0 . 5 ) <nl> + { } <nl> + <nl> + RDB_IMPL_SERIALIZABLE_6_FOR_CLUSTER ( backfill_config_t , <nl> + item_queue_mem_size , item_chunk_mem_size , pre_item_queue_mem_size , <nl> + pre_item_chunk_mem_size , write_queue_count , write_queue_trickle_fraction ) ; <nl> + <nl> RDB_IMPL_SERIALIZABLE_5_FOR_CLUSTER ( backfiller_bcard_t : : intro_2_t , <nl> common_version , pre_items_mailbox , begin_session_mailbox , end_session_mailbox , <nl> ack_items_mailbox ) ; <nl> <nl> - RDB_IMPL_SERIALIZABLE_6_FOR_CLUSTER ( backfiller_bcard_t : : intro_1_t , <nl> - initial_version , initial_version_history , intro_mailbox , items_mailbox , <nl> + RDB_IMPL_SERIALIZABLE_7_FOR_CLUSTER ( backfiller_bcard_t : : intro_1_t , <nl> + config , initial_version , initial_version_history , intro_mailbox , items_mailbox , <nl> ack_end_session_mailbox , ack_pre_items_mailbox ) ; <nl> <nl> RDB_IMPL_SERIALIZABLE_2_FOR_CLUSTER ( backfiller_bcard_t , region , registrar ) ; <nl> mmm a / src / clustering / immediate_consistency / backfill_metadata . hpp <nl> ppp b / src / clustering / immediate_consistency / backfill_metadata . hpp <nl> <nl> # include " rdb_protocol / protocol . hpp " <nl> # include " rpc / mailbox / typed . hpp " <nl> <nl> + / * ` backfill_config_t ` contains parameters for tuning the backfill ' s performance and <nl> + memory usage . Mostly it ' s for unit testing purposes ; currently we always use fixed values <nl> + in release mode , but the unit tests use smaller queue sizes to trigger different edge <nl> + cases . * / <nl> + class backfill_config_t { <nl> + public : <nl> + / * The default constructor assigns reasonable defaults * / <nl> + backfill_config_t ( ) ; <nl> + <nl> + / * The maximum amount of RAM that can be used for the items queued in memory on the <nl> + backfillee . * / <nl> + size_t item_queue_mem_size ; <nl> + <nl> + / * The maximum size , in bytes , of a chunk of items sent over the network from the <nl> + backfiller to the backfillee . * / <nl> + size_t item_chunk_mem_size ; <nl> + <nl> + / * The maximum amount of RAM that can be used for the pre - items queued in memory on <nl> + the backfiller . * / <nl> + size_t pre_item_queue_mem_size ; <nl> + <nl> + / * The maximum size , in bytes , of a chunk of pre - items sent over the network from the <nl> + backfillee to the backfiller . * / <nl> + size_t pre_item_chunk_mem_size ; <nl> + <nl> + / * The maximum number of writes that the ` remote_replicator_client_t ` will allow to <nl> + queue up before it pauses the backfill to perform the writes * / <nl> + size_t write_queue_count ; <nl> + <nl> + / * Every time the ` remote_replicator_client_t ` performs a queued write , it allows <nl> + ` write_queue_trickle_fraction ` new writes to be added to the back of the queue . So <nl> + this must be between 0 and 1 . Higher values improve streaming write performance , but <nl> + make the backfill take longer . * / <nl> + double write_queue_trickle_fraction ; <nl> + } ; <nl> + <nl> + RDB_DECLARE_SERIALIZABLE ( backfill_config_t ) ; <nl> + <nl> / * The backfiller publishes a ` backfiller_bcard_t ` which the backfillee uses to contact <nl> it . The member types of ` backfiller_bcard_t ` describe the communications protocol between <nl> the backfiller and the backfillee . <nl> class backfiller_bcard_t { <nl> <nl> class intro_1_t { <nl> public : <nl> + backfill_config_t config ; <nl> region_map_t < version_t > initial_version ; <nl> branch_history_t initial_version_history ; <nl> mailbox_t < void ( intro_2_t ) > : : address_t intro_mailbox ; <nl> mmm a / src / clustering / immediate_consistency / backfillee . cc <nl> ppp b / src / clustering / immediate_consistency / backfillee . cc <nl> <nl> <nl> # include " kh_debug . hpp " <nl> <nl> - / * ` PRE_ITEM_PIPELINE_SIZE ` is the maximum combined size ( as computed by <nl> - ` get_mem_size ( ) ` ) of the pre - items that we send to the backfiller that it hasn ' t consumed <nl> - yet . So the other server may use up to this size for its pre - item queue . <nl> - ` PRE_ITEM_CHUNK_SIZE ` is the typical size of a pre - item message we send over the network . <nl> - * / <nl> - static const size_t PRE_ITEM_PIPELINE_SIZE = 4 * MEGABYTE ; <nl> - static const size_t PRE_ITEM_CHUNK_SIZE = 100 * KILOBYTE ; <nl> - <nl> / * ` ITEM_ACK_INTERVAL_MS ` controls how often we send acknowledgements back to the <nl> backfiller . If it ' s too short , we ' ll waste resources sending lots of tiny <nl> acknowledgements ; if it ' s too long , the pipeline might stall . * / <nl> backfillee_t : : backfillee_t ( <nl> branch_history_manager_t * _branch_history_manager , <nl> store_view_t * _store , <nl> const backfiller_bcard_t & backfiller , <nl> + const backfill_config_t & _backfill_config , <nl> signal_t * interruptor ) : <nl> mailbox_manager ( _mailbox_manager ) , <nl> branch_history_manager ( _branch_history_manager ) , <nl> store ( _store ) , <nl> - pre_item_throttler ( PRE_ITEM_PIPELINE_SIZE ) , <nl> + backfill_config ( _backfill_config ) , <nl> + pre_item_throttler ( backfill_config . pre_item_queue_mem_size ) , <nl> pre_item_throttler_acq ( & pre_item_throttler , 0 ) , <nl> items_mailbox ( mailbox_manager , <nl> std : : bind ( & backfillee_t : : on_items , this , ph : : _1 , ph : : _2 , ph : : _3 , ph : : _4 ) ) , <nl> backfillee_t : : backfillee_t ( <nl> guarantee ( store - > get_region ( ) . end = = backfiller . region . end ) ; <nl> <nl> backfiller_bcard_t : : intro_1_t our_intro ; <nl> + our_intro . config = backfill_config ; <nl> our_intro . ack_pre_items_mailbox = ack_pre_items_mailbox . get_address ( ) ; <nl> our_intro . items_mailbox = items_mailbox . get_address ( ) ; <nl> our_intro . ack_end_session_mailbox = ack_end_session_mailbox . get_address ( ) ; <nl> void backfillee_t : : send_pre_items ( auto_drainer_t : : lock_t keepalive ) { <nl> while ( pre_item_sent_threshold ! = store - > get_region ( ) . inner . right ) { <nl> / * Wait until there ' s room in the semaphore for the chunk we ' re about to <nl> process * / <nl> - new_semaphore_acq_t sem_acq ( & pre_item_throttler , PRE_ITEM_CHUNK_SIZE ) ; <nl> + new_semaphore_acq_t sem_acq ( <nl> + & pre_item_throttler , backfill_config . pre_item_chunk_mem_size ) ; <nl> wait_interruptible ( <nl> sem_acq . acquisition_signal ( ) , keepalive . get_drain_signal ( ) ) ; <nl> <nl> void backfillee_t : : send_pre_items ( auto_drainer_t : : lock_t keepalive ) { <nl> subregion . inner . left = pre_item_sent_threshold . key ( ) ; <nl> <nl> / * Copy pre - items from the store into ` chunk ` until the total size hits <nl> - ` PRE_ITEM_CHUNK_SIZE ` or we finish the range * / <nl> + ` backfill_config . pre_item_chunk_mem_size ` or we finish the range * / <nl> backfill_item_seq_t < backfill_pre_item_t > chunk ( <nl> store - > get_region ( ) . beg , store - > get_region ( ) . end , <nl> pre_item_sent_threshold ) ; <nl> <nl> class consumer_t : public store_view_t : : backfill_pre_item_consumer_t { <nl> public : <nl> - consumer_t ( backfill_item_seq_t < backfill_pre_item_t > * _chunk ) : <nl> - chunk ( _chunk ) { } <nl> + consumer_t ( <nl> + backfill_item_seq_t < backfill_pre_item_t > * _chunk , <nl> + const backfill_config_t * _config ) : <nl> + chunk ( _chunk ) , config ( _config ) { } <nl> continue_bool_t on_pre_item ( backfill_pre_item_t & & item ) THROWS_NOTHING { <nl> chunk - > push_back ( std : : move ( item ) ) ; <nl> - if ( chunk - > get_mem_size ( ) < PRE_ITEM_CHUNK_SIZE ) { <nl> + if ( chunk - > get_mem_size ( ) < config - > pre_item_chunk_mem_size ) { <nl> return continue_bool_t : : CONTINUE ; <nl> } else { <nl> return continue_bool_t : : ABORT ; <nl> void backfillee_t : : send_pre_items ( auto_drainer_t : : lock_t keepalive ) { <nl> return continue_bool_t : : CONTINUE ; <nl> } <nl> backfill_item_seq_t < backfill_pre_item_t > * chunk ; <nl> - } callback ( & chunk ) ; <nl> + backfill_config_t const * const config ; <nl> + } callback ( & chunk , & backfill_config ) ; <nl> <nl> store - > send_backfill_pre ( intro . common_version . mask ( subregion ) , & callback , <nl> keepalive . get_drain_signal ( ) ) ; <nl> mmm a / src / clustering / immediate_consistency / backfillee . hpp <nl> ppp b / src / clustering / immediate_consistency / backfillee . hpp <nl> class backfillee_t : public home_thread_mixin_debug_only_t { <nl> branch_history_manager_t * _branch_history_manager , <nl> store_view_t * _store , <nl> const backfiller_bcard_t & backfiller , <nl> + const backfill_config_t & backfill_config , <nl> signal_t * interruptor ) ; <nl> ~ backfillee_t ( ) ; <nl> <nl> class backfillee_t : public home_thread_mixin_debug_only_t { <nl> mailbox_manager_t * const mailbox_manager ; <nl> branch_history_manager_t * const branch_history_manager ; <nl> store_view_t * const store ; <nl> + backfill_config_t const backfill_config ; <nl> <nl> backfiller_bcard_t : : intro_2_t intro ; <nl> <nl> mmm a / src / clustering / immediate_consistency / backfiller . cc <nl> ppp b / src / clustering / immediate_consistency / backfiller . cc <nl> <nl> # include " rdb_protocol / protocol . hpp " <nl> # include " store_view . hpp " <nl> <nl> - / * ` ITEM_PIPELINE_SIZE ` is the maximum combined size of the items that we send to the <nl> - backfillee that it hasn ' t consumed yet . ` ITEM_CHUNK_SIZE ` is the typical size of an item <nl> - message we send over the network . * / <nl> - static const size_t ITEM_PIPELINE_SIZE = 4 * MEGABYTE ; <nl> - static const size_t ITEM_CHUNK_SIZE = 100 * KILOBYTE ; <nl> - <nl> backfiller_t : : backfiller_t ( <nl> mailbox_manager_t * _mailbox_manager , <nl> branch_history_manager_t * _branch_history_manager , <nl> backfiller_t : : client_t : : client_t ( <nl> full_region ( intro . initial_version . get_domain ( ) ) , <nl> pre_items ( full_region . beg , full_region . end , <nl> key_range_t : : right_bound_t ( full_region . inner . left ) ) , <nl> - item_throttler ( ITEM_PIPELINE_SIZE ) , <nl> + item_throttler ( intro . config . item_queue_mem_size ) , <nl> item_throttler_acq ( & item_throttler , 0 ) , <nl> pre_items_mailbox ( parent - > mailbox_manager , <nl> std : : bind ( & client_t : : on_pre_items , this , ph : : _1 , ph : : _2 , ph : : _3 ) ) , <nl> class backfiller_t : : client_t : : session_t { <nl> while ( threshold ! = parent - > full_region . inner . right ) { <nl> / * Wait until there ' s room in the semaphore for the chunk we ' re about to <nl> process * / <nl> - new_semaphore_acq_t sem_acq ( & parent - > item_throttler , ITEM_CHUNK_SIZE ) ; <nl> + new_semaphore_acq_t sem_acq ( <nl> + & parent - > item_throttler , parent - > intro . config . item_chunk_mem_size ) ; <nl> wait_interruptible ( <nl> sem_acq . acquisition_signal ( ) , keepalive . get_drain_signal ( ) ) ; <nl> <nl> class backfiller_t : : client_t : : session_t { <nl> ` chunk ` and in ` metainfo ` . * / <nl> class consumer_t : public store_view_t : : backfill_item_consumer_t { <nl> public : <nl> - consumer_t ( backfill_item_seq_t < backfill_item_t > * _chunk , <nl> - region_map_t < version_t > * _metainfo ) : <nl> - chunk ( _chunk ) , metainfo ( _metainfo ) { } <nl> + consumer_t ( <nl> + backfill_item_seq_t < backfill_item_t > * _chunk , <nl> + region_map_t < version_t > * _metainfo , <nl> + const backfill_config_t * _config ) : <nl> + chunk ( _chunk ) , metainfo ( _metainfo ) , config ( _config ) { } <nl> continue_bool_t on_item ( <nl> const region_map_t < binary_blob_t > & item_metainfo , <nl> backfill_item_t & & item ) THROWS_NOTHING { <nl> class backfiller_t : : client_t : : session_t { <nl> rassert ( ! item . range . is_empty ( ) ) ; <nl> on_metainfo ( item_metainfo , item . range . right ) ; <nl> chunk - > push_back ( std : : move ( item ) ) ; <nl> - if ( chunk - > get_mem_size ( ) < ITEM_CHUNK_SIZE ) { <nl> + if ( chunk - > get_mem_size ( ) < config - > item_chunk_mem_size ) { <nl> return continue_bool_t : : CONTINUE ; <nl> } else { <nl> return continue_bool_t : : ABORT ; <nl> class backfiller_t : : client_t : : session_t { <nl> mask . inner . right = new_threshold ; <nl> metainfo - > concat ( to_version_map ( new_metainfo . mask ( mask ) ) ) ; <nl> } <nl> - backfill_item_seq_t < backfill_item_t > * chunk ; <nl> - region_map_t < version_t > * metainfo ; <nl> - } consumer ( & chunk , & metainfo ) ; <nl> + backfill_item_seq_t < backfill_item_t > * const chunk ; <nl> + region_map_t < version_t > * const metainfo ; <nl> + backfill_config_t const * const config ; <nl> + } consumer ( & chunk , & metainfo , & parent - > intro . config ) ; <nl> <nl> parent - > parent - > store - > send_backfill ( <nl> parent - > common_version . mask ( subregion ) , & producer , & consumer , <nl> mmm a / src / clustering / immediate_consistency / remote_replicator_client . cc <nl> ppp b / src / clustering / immediate_consistency / remote_replicator_client . cc <nl> <nl> <nl> # include " kh_debug . hpp " <nl> <nl> - / * Maximum number of writes we can queue up in each cycle of the backfill . When we hit <nl> - this number , we ' ll interrupt the backfill and drain the queue . * / <nl> - static const int MAX_QUEUED_WRITES = 1000 ; <nl> - <nl> - / * Every time we perform a queued write , we ' ll let ` QUEUE_TRICKLE_FRACTION ` new writes be <nl> - added to the back of the queue . So ` QUEUE_TRICKLE_FRACTION ` should be less than 1 , to <nl> - ensure that the queue must drain eventually . Higher values will improve performance of <nl> - streaming writes ; lower numbers will make the backfill finish faster . * / <nl> - static const double QUEUE_TRICKLE_FRACTION = 0 . 5 ; <nl> - <nl> / * Sometimes we ' ll receive the same write as part of our stream of writes from the <nl> dispatcher and as part of our backfill from the backfiller . To avoid corruption , we need <nl> to be sure that we don ' t apply the write twice . ` backfill_end_timestamps_t ` tracks which <nl> class remote_replicator_client_t : : backfill_end_timestamps_t { <nl> remote_replicator_client_t : : remote_replicator_client_t ( <nl> / * RSI ( raft ) : Respect backfill_throttler * / <nl> UNUSED backfill_throttler_t * backfill_throttler , <nl> + const backfill_config_t & backfill_config , <nl> mailbox_manager_t * mailbox_manager , <nl> const server_id_t & server_id , <nl> <nl> remote_replicator_client_t : : remote_replicator_client_t ( <nl> they arrive because ` discard_threshold_ ` is the left boundary . * / <nl> <nl> backfillee_t backfillee ( mailbox_manager , branch_history_manager , store , <nl> - replica_bcard . backfiller_bcard , interruptor ) ; <nl> + replica_bcard . backfiller_bcard , backfill_config , interruptor ) ; <nl> <nl> / * We acquire ` rwlock_ ` to lock out writes while we ' re writing to ` region_ * _ ` , <nl> ` queue_fun_ ` , and ` replica_ ` , and for the last stage of draining the queue . * / <nl> remote_replicator_client_t : : remote_replicator_client_t ( <nl> / * Backfill in lexicographical order until the queue hits a certain size * / <nl> class callback_t : public backfillee_t : : callback_t { <nl> public : <nl> - callback_t ( std : : queue < queue_entry_t > * _queue , <nl> - const key_range_t : : right_bound_t & _right_bound ) : <nl> - queue ( _queue ) , right_bound ( _right_bound ) { } <nl> + callback_t ( <nl> + std : : queue < queue_entry_t > * _queue , <nl> + const key_range_t : : right_bound_t & _right_bound , <nl> + const backfill_config_t * _config ) : <nl> + queue ( _queue ) , right_bound ( _right_bound ) , config ( _config ) { } <nl> bool on_progress ( const region_map_t < version_t > & chunk ) THROWS_NOTHING { <nl> rassert ( key_range_t : : right_bound_t ( chunk . get_domain ( ) . inner . left ) = = <nl> right_bound ) ; <nl> remote_replicator_client_t : : remote_replicator_client_t ( <nl> backfill_end_timestamps . combine ( <nl> region_map_transform < version_t , state_timestamp_t > ( chunk , <nl> [ ] ( const version_t & version ) { return version . timestamp ; } ) ) ; <nl> - return ( queue - > size ( ) < MAX_QUEUED_WRITES ) ; <nl> + return ( queue - > size ( ) < config - > write_queue_count ) ; <nl> } <nl> std : : queue < queue_entry_t > * queue ; <nl> backfill_end_timestamps_t backfill_end_timestamps ; <nl> key_range_t : : right_bound_t right_bound ; <nl> - } callback ( & queue , key_range_t : : right_bound_t ( region_queueing_ . inner . left ) ) ; <nl> + backfill_config_t const * const config ; <nl> + } callback ( <nl> + & queue , <nl> + key_range_t : : right_bound_t ( region_queueing_ . inner . left ) , <nl> + & backfill_config ) ; <nl> <nl> khd_all ( " begin backfillee . go ( ) from " , key_range_t : : right_bound_t ( region_queueing_ . inner . left ) ) ; <nl> <nl> remote_replicator_client_t : : remote_replicator_client_t ( <nl> but we pop fewer entries off of ` ack_queue ` than off of the main queue . <nl> This slows down the pace of incoming writes from the primary so that we <nl> can be sure that the queue will eventually drain . * / <nl> - acks_to_release + = QUEUE_TRICKLE_FRACTION ; <nl> + acks_to_release + = backfill_config . write_queue_trickle_fraction ; <nl> if ( acks_to_release > = 1 & & ! ack_queue . empty ( ) ) { <nl> acks_to_release - = 1 ; <nl> ack_queue . front ( ) - > pulse ( ) ; <nl> mmm a / src / clustering / immediate_consistency / remote_replicator_client . hpp <nl> ppp b / src / clustering / immediate_consistency / remote_replicator_client . hpp <nl> class remote_replicator_client_t { <nl> <nl> remote_replicator_client_t ( <nl> backfill_throttler_t * backfill_throttler , <nl> + const backfill_config_t & backfill_config , <nl> mailbox_manager_t * mailbox_manager , <nl> const server_id_t & server_id , <nl> <nl> mmm a / src / clustering / table_contract / exec_secondary . cc <nl> ppp b / src / clustering / table_contract / exec_secondary . cc <nl> void secondary_execution_t : : run ( auto_drainer_t : : lock_t keepalive ) { <nl> / * Backfill and start streaming from the primary . * / <nl> remote_replicator_client_t remote_replicator_client ( <nl> context - > backfill_throttler , <nl> + backfill_config_t ( ) , <nl> context - > mailbox_manager , <nl> context - > server_id , <nl> branch , <nl> mmm a / src / unittest / clustering_backfill . cc <nl> ppp b / src / unittest / clustering_backfill . cc <nl> TPTEST ( ClusteringBackfill , BackfillTest ) { <nl> & branch_history_manager , <nl> & backfillee_store , <nl> backfiller . get_business_card ( ) , <nl> + backfill_config_t ( ) , <nl> & non_interruptor ) ; <nl> class callback_t : public backfillee_t : : callback_t { <nl> public : <nl> mmm a / src / unittest / clustering_branch . cc <nl> ppp b / src / unittest / clustering_branch . cc <nl> void run_backfill_test ( <nl> cond_t interruptor ; <nl> remote_replicator_client_t remote_replicator_client ( <nl> & backfill_throttler , <nl> + backfill_config_t ( ) , <nl> cluster - > get_mailbox_manager ( ) , <nl> generate_uuid ( ) , <nl> dispatcher - > get_branch_id ( ) , <nl> mmm a / src / unittest / rdb_backfill . cc <nl> ppp b / src / unittest / rdb_backfill . cc <nl> void run_backfill_test ( <nl> size_t value_padding_length , <nl> int num_initial , <nl> int num_step , <nl> - bool stream_during_backfill ) { <nl> + bool stream_during_backfill , <nl> + const backfill_config_t & backfill_config ) { <nl> <nl> khd_all ( " begin backfill test " ) ; <nl> <nl> void run_backfill_test ( <nl> backfill_throttler_t backfill_throttler ; <nl> khd_all ( " begin backfill 1 - > 2 " ) ; <nl> remote_replicator_client_t remote_replicator_client_2 ( & backfill_throttler , <nl> - cluster . get_mailbox_manager ( ) , generate_uuid ( ) , <nl> + backfill_config , cluster . get_mailbox_manager ( ) , generate_uuid ( ) , <nl> dispatcher . get_branch_id ( ) , remote_replicator_server . get_bcard ( ) , <nl> local_replicator . get_replica_bcard ( ) , & store2 . store , & bhm , <nl> & non_interruptor ) ; <nl> khd_all ( " end backfill 1 - > 2 " ) ; <nl> khd_all ( " begin backfill 1 - > 3 " ) ; <nl> remote_replicator_client_t remote_replicator_client_3 ( & backfill_throttler , <nl> - cluster . get_mailbox_manager ( ) , generate_uuid ( ) , <nl> + backfill_config , cluster . get_mailbox_manager ( ) , generate_uuid ( ) , <nl> dispatcher . get_branch_id ( ) , remote_replicator_server . get_bcard ( ) , <nl> local_replicator . get_replica_bcard ( ) , & store3 . store , & bhm , <nl> & non_interruptor ) ; <nl> void run_backfill_test ( <nl> khd_all ( " begin backfill 2 - > 1 " ) ; <nl> backfill_throttler_t backfill_throttler ; <nl> remote_replicator_client_t remote_replicator_client ( & backfill_throttler , <nl> - cluster . get_mailbox_manager ( ) , generate_uuid ( ) , <nl> + backfill_config , cluster . get_mailbox_manager ( ) , generate_uuid ( ) , <nl> dispatcher . get_branch_id ( ) , remote_replicator_server . get_bcard ( ) , <nl> local_replicator . get_replica_bcard ( ) , & store1 . store , & bhm , <nl> & non_interruptor ) ; <nl> void run_backfill_test ( <nl> khd_all ( " begin backfill 1 - > 3 " ) ; <nl> backfill_throttler_t backfill_throttler ; <nl> remote_replicator_client_t remote_replicator_client ( & backfill_throttler , <nl> - cluster . get_mailbox_manager ( ) , generate_uuid ( ) , <nl> + backfill_config , cluster . get_mailbox_manager ( ) , generate_uuid ( ) , <nl> dispatcher . get_branch_id ( ) , remote_replicator_server . get_bcard ( ) , <nl> local_replicator . get_replica_bcard ( ) , & store3 . store , & bhm , <nl> & non_interruptor ) ; <nl> void run_backfill_test ( <nl> } <nl> } <nl> <nl> + backfill_config_t unlimited_queues_config ( ) { <nl> + backfill_config_t c ; <nl> + c . item_queue_mem_size = GIGABYTE ; <nl> + c . pre_item_queue_mem_size = GIGABYTE ; <nl> + c . write_queue_count = 1000000 ; <nl> + return c ; <nl> + } <nl> + <nl> TPTEST ( RDBBackfill , DenseChangesAndStreaming ) { <nl> - run_backfill_test ( 100 , 3000 , 1000 , true ) ; <nl> + run_backfill_test ( 100 , 3000 , 1000 , true , unlimited_queues_config ( ) ) ; <nl> } <nl> <nl> TPTEST ( RDBBackfill , SparseChanges ) { <nl> - run_backfill_test ( 100 , 1000 , 10 , false ) ; <nl> + run_backfill_test ( 100 , 1000 , 10 , false , unlimited_queues_config ( ) ) ; <nl> } <nl> <nl> TPTEST ( RDBBackfill , LargeValues ) { <nl> - run_backfill_test ( MEGABYTE , 100 , 10 , true ) ; <nl> + run_backfill_test ( MEGABYTE , 100 , 10 , true , unlimited_queues_config ( ) ) ; <nl> } <nl> <nl> TPTEST ( RDBBackfill , SmallValues ) { <nl> - run_backfill_test ( 1 , 100 , 10 , true ) ; <nl> + run_backfill_test ( 1 , 100 , 10 , true , unlimited_queues_config ( ) ) ; <nl> } <nl> <nl> / * <nl> TPTEST ( RDBBackfill , LargeTable ) { <nl> * / <nl> <nl> TPTEST ( RDBBackfill , EmptyTable ) { <nl> - run_backfill_test ( 100 , 0 , 0 , false ) ; <nl> + run_backfill_test ( 100 , 0 , 0 , false , unlimited_queues_config ( ) ) ; <nl> } <nl> <nl> TPTEST ( RDBBackfill , NearEmptyTable ) { <nl> - run_backfill_test ( 100 , 1 , 1 , true ) ; <nl> + run_backfill_test ( 100 , 1 , 1 , true , unlimited_queues_config ( ) ) ; <nl> + } <nl> + <nl> + TPTEST ( RDBBackfill , FillItemQueue ) { <nl> + backfill_config_t c = unlimited_queues_config ( ) ; <nl> + c . item_queue_mem_size = 1000 ; <nl> + c . item_queue_chunk_size = 100 ; <nl> + run_backfill_test ( 100 , 3000 , 1000 , true , c ) ; <nl> + } <nl> + <nl> + TPTEST ( RDBBackfill , FillPreItemQueue ) { <nl> + backfill_config_t c = unlimited_queues_config ( ) ; <nl> + c . pre_item_queue_mem_size = 1000 ; <nl> + c . pre_item_queue_chunk_size = 100 ; <nl> + run_backfill_test ( 100 , 3000 , 1000 , true , c ) ; <nl> + } <nl> + <nl> + TPTEST ( RDBBackfill , FillWriteQueue ) { <nl> + backfill_config_t c = unlimited_queues_config ( ) ; <nl> + c . write_queue_count = 3 ; <nl> + run_backfill_test ( 100 , 3000 , 1000 , true , c ) ; <nl> + } <nl> + <nl> + TPTEST ( RDBBackfill , TinyChunks ) { <nl> + backfill_config_t c ; <nl> + c . item_queue_mem_size = 0 ; <nl> + c . item_chunk_mem_size = 0 ; <nl> + c . pre_item_queue_mem_size = 0 ; <nl> + c . pre_item_chunk_mem_size = 0 ; <nl> + c . write_queue_count = 0 ; <nl> + run_backfill_test ( 1 , 100 , 10 , true , c ) ; <nl> } <nl> <nl> } / * namespace unittest * / <nl>
Thread backfill_config_t through backfilling code so that unit tests can tweak parameters to force other code paths .
rethinkdb/rethinkdb
0dcec8c1eb3b703e90f1345eb907f2e0bf2015ed
2015-04-11T01:00:40Z
mmm a / tensorflow / python / ops / image_ops_impl . py <nl> ppp b / tensorflow / python / ops / image_ops_impl . py <nl> def rgb_to_yuv ( images ) : <nl> value of the pixels . <nl> The output is only well defined if the value in images are in [ 0 , 1 ] . <nl> <nl> - Usage Example : <nl> - <nl> - > > > x = [ [ [ 0 . 1 , 0 . 2 , 0 . 3 ] , <nl> - . . . [ 0 . 4 , 0 . 5 , 0 . 6 ] ] , <nl> - . . . [ [ 0 . 7 , 0 . 8 , 0 . 9 ] , <nl> - . . . [ 0 . 10 , 0 . 11 , 0 . 12 ] ] ] <nl> - > > > tf . image . rgb_to_yuv ( x ) <nl> - < tf . Tensor : shape = ( 2 , 2 , 3 ) , dtype = float32 , numpy = <nl> - array ( [ [ [ 0 . 1815 , 0 . 05831515 , - 0 . 07149857 ] , <nl> - [ 0 . 4815 , 0 . 05831517 , - 0 . 07149856 ] ] , <nl> - [ [ 0 . 7815 , 0 . 05831515 , - 0 . 07149857 ] , <nl> - [ 0 . 10815 , 0 . 00583152 , - 0 . 00714985 ] ] ] , dtype = float32 ) > <nl> - <nl> Args : <nl> images : 2 - D or higher rank . Image data to convert . Last dimension must be <nl> size 3 . <nl>
Remove the failing test on macos .
tensorflow/tensorflow
a12180b8025ca4b9bb7d9c795b4bcf8c42640df6
2020-03-17T19:12:24Z
mmm a / src / arm64 / dom_parser_implementation . cpp <nl> ppp b / src / arm64 / dom_parser_implementation . cpp <nl> WARN_UNUSED error_code dom_parser_implementation : : stage1 ( const uint8_t * _buf , si <nl> this - > len = _len ; <nl> return arm64 : : stage1 : : json_structural_indexer : : index < 64 > ( buf , len , * this , streaming ) ; <nl> } <nl> - <nl> + # include " generic / stage1 / utf8_validator . h " <nl> } / / namespace arm64 <nl> } / / namespace simdjson <nl> <nl> mmm a / src / generic / stage1 / buf_block_reader . h <nl> ppp b / src / generic / stage1 / buf_block_reader . h <nl> struct buf_block_reader { <nl> really_inline size_t block_index ( ) ; <nl> really_inline bool has_full_block ( ) const ; <nl> really_inline const uint8_t * full_block ( ) const ; <nl> + really_inline bool has_remainder ( ) const { <nl> + return idx < len ; <nl> + } <nl> / * * <nl> * Get the last block , padded with spaces . <nl> * <nl> new file mode 100644 <nl> index 000000000 . . 384cab0e7 <nl> mmm / dev / null <nl> ppp b / src / generic / stage1 / utf8_validator . h <nl> <nl> + namespace stage1 { <nl> + / * * <nl> + * Validates that the string is actual UTF - 8 . <nl> + * / <nl> + template < class checker > <nl> + bool utf8_validate ( const uint8_t * input , size_t length ) { <nl> + checker c { } ; <nl> + buf_block_reader < 64 > reader ( input , length ) ; <nl> + while ( reader . has_full_block ( ) ) { <nl> + simd : : simd8x64 < uint8_t > in ( reader . full_block ( ) ) ; <nl> + c . check_next_input ( in ) ; <nl> + reader . advance ( ) ; <nl> + } <nl> + <nl> + if ( likely ( reader . has_remainder ( ) ) ) { <nl> + uint8_t block [ 64 ] { } ; <nl> + reader . get_remainder ( block ) ; <nl> + simd : : simd8x64 < uint8_t > in ( block ) ; <nl> + c . check_next_input ( in ) ; <nl> + reader . advance ( ) ; <nl> + } <nl> + return c . errors ( ) = = error_code : : SUCCESS ; <nl> + } <nl> + <nl> + bool utf8_validate ( const char * input , size_t length ) { <nl> + return utf8_validate < utf8_checker > ( ( const uint8_t * ) input , length ) ; <nl> + } <nl> + <nl> + } / / namespace stage1 <nl> \ No newline at end of file <nl> mmm a / src / haswell / dom_parser_implementation . cpp <nl> ppp b / src / haswell / dom_parser_implementation . cpp <nl> WARN_UNUSED error_code dom_parser_implementation : : stage1 ( const uint8_t * _buf , si <nl> this - > len = _len ; <nl> return haswell : : stage1 : : json_structural_indexer : : index < 128 > ( _buf , _len , * this , streaming ) ; <nl> } <nl> - <nl> + # include " generic / stage1 / utf8_validator . h " <nl> } / / namespace haswell <nl> } / / namespace simdjson <nl> UNTARGET_REGION <nl> mmm a / src / westmere / dom_parser_implementation . cpp <nl> ppp b / src / westmere / dom_parser_implementation . cpp <nl> WARN_UNUSED error_code dom_parser_implementation : : stage1 ( const uint8_t * _buf , si <nl> this - > len = _len ; <nl> return westmere : : stage1 : : json_structural_indexer : : index < 64 > ( _buf , _len , * this , streaming ) ; <nl> } <nl> - <nl> + # include " generic / stage1 / utf8_validator . h " <nl> } / / namespace westmere <nl> } / / namespace simdjson <nl> UNTARGET_REGION <nl>
Ok .
simdjson/simdjson
04139eb82ea5f432c7d779fe86c6d46313060009
2020-06-21T21:05:55Z
mmm a / lib / SILGen / SILGenExpr . cpp <nl> ppp b / lib / SILGen / SILGenExpr . cpp <nl> void SILGenFunction : : emitMemberInitializers ( VarDecl * selfDecl , <nl> for ( auto member : nominal - > getMembers ( ) ) { <nl> / / Find pattern binding declarations that have initializers . <nl> auto pbd = dyn_cast < PatternBindingDecl > ( member ) ; <nl> - if ( ! pbd ) continue ; <nl> + if ( ! pbd | | pbd - > isStatic ( ) ) continue ; <nl> <nl> auto init = pbd - > getInit ( ) ; <nl> if ( ! init ) continue ; <nl>
fix rdar : / / 15821990 - Don ' t emit default value for type var in instance init ( ) body .
apple/swift
eacb823fd5d4611bb56bbbd9ab0354d21e5281cd
2014-01-15T05:31:43Z
mmm a / include / internal / catch_stream . hpp <nl> ppp b / include / internal / catch_stream . hpp <nl> namespace Catch { <nl> } <nl> } <nl> <nl> - # ifndef CATCH_CONFIG_NOSTDOUT / / If you # define this you must implement this functions <nl> + # ifndef CATCH_CONFIG_NOSTDOUT / / If you # define this you must implement these functions <nl> std : : ostream & cout ( ) { <nl> return std : : cout ; <nl> } <nl>
Merge pull request from nabijaczleweli / patch - 1
catchorg/Catch2
d758428fe297655e558a86cc6a013fcb1bcc8c7d
2015-10-26T14:47:29Z
mmm a / xbmc / linux / PosixMountProvider . cpp <nl> ppp b / xbmc / linux / PosixMountProvider . cpp <nl> std : : vector < CStdString > CPosixMountProvider : : GetDiskUsage ( ) <nl> return result ; <nl> } <nl> <nl> + bool CPosixMountProvider : : Eject ( CStdString mountpath ) <nl> + { <nl> + / / just go ahead and try to umount the disk <nl> + / / if it does umount , life is good , if not , no loss . <nl> + std : : string cmd = " umount " + mountpath ; <nl> + system ( cmd . c_str ( ) ) ; <nl> + <nl> + return true ; <nl> + } <nl> + <nl> bool CPosixMountProvider : : PumpDriveChangeEvents ( IStorageEventsCallback * callback ) <nl> { <nl> VECSOURCES drives ; <nl> mmm a / xbmc / linux / PosixMountProvider . h <nl> ppp b / xbmc / linux / PosixMountProvider . h <nl> class CPosixMountProvider : public IStorageProvider <nl> <nl> virtual std : : vector < CStdString > GetDiskUsage ( ) ; <nl> <nl> - virtual bool Eject ( CStdString mountpath ) { return false ; } <nl> + virtual bool Eject ( CStdString mountpath ) ; <nl> <nl> virtual bool PumpDriveChangeEvents ( IStorageEventsCallback * callback ) ; <nl> private : <nl> mmm a / xbmc / storage / linux / UDevProvider . cpp <nl> ppp b / xbmc / storage / linux / UDevProvider . cpp <nl> void CUDevProvider : : GetRemovableDrives ( VECSOURCES & removableDrives ) <nl> <nl> bool CUDevProvider : : Eject ( CStdString mountpath ) <nl> { <nl> - return false ; <nl> + / / just go ahead and try to umount the disk <nl> + / / if it does umount , life is good , if not , no loss . <nl> + std : : string cmd = " umount " + mountpath ; <nl> + system ( cmd . c_str ( ) ) ; <nl> + <nl> + return true ; <nl> } <nl> <nl> std : : vector < CStdString > CUDevProvider : : GetDiskUsage ( ) <nl>
fixed context menu ' remove safely ' selection
xbmc/xbmc
4051f2acb5def5f928277195e210aeb488910c8b
2014-02-05T20:25:44Z
mmm a / AUTHORS <nl> ppp b / AUTHORS <nl> Developers : <nl> Rolando Abarca <nl> Javascript Binding and testjs <nl> <nl> - fape <nl> - add Hungarian language support <nl> - <nl> chenium <nl> fix a bug that CCRenderTexture can not work when coming to foreground on Android <nl> <nl> Developers : <nl> johnangel <nl> OpenGL framebuffer access violation fix . <nl> <nl> - Peter Farkas ( fape ) <nl> - contributes Marmalade port for gles20 branch . <nl> - <nl> + Peter Farkas ( fape ) <nl> + contributes Marmalade port for gles20 branch <nl> + add Hungarian language support <nl> + <nl> Retired Core Developers : <nl> WenSheng Yang <nl> Author of windows port , CCTextField , <nl>
cosmetic AUTHORS
cocos2d/cocos2d-x
ce87451fbca38addef13c71adaf323bef5c6a9be
2012-12-06T09:39:42Z
mmm a / docs / LibraryEvolution . rst <nl> ppp b / docs / LibraryEvolution . rst <nl> layout . <nl> accessors of a property are fine , but those that provide new entry points <nl> are trickier . <nl> <nl> - Like top - level constants , it is * not * safe to change a ` ` let ` ` property into a <nl> - variable or vice versa . Properties declared with ` ` let ` ` are assumed not to <nl> - change for the entire lifetime of the program once they have been initialized . <nl> - <nl> It is not safe to add or remove ` ` mutating ` ` or ` ` nonmutating ` ` from a member <nl> or accessor within a struct . These modifiers are not ` versioned attributes <nl> < versioned attribute > ` and as such there is no safety guarantee for a client <nl> deploying against an earlier version of the library . <nl> <nl> <nl> + Methods and Initializers <nl> + mmmmmmmmmmmmmmmmmmmmmmmm <nl> + <nl> + For the most part struct methods and initializers are treated exactly like top - level functions . They permit all of the same modifications and can also <nl> + be marked ` ` @ inlineable ` ` , with the same restrictions . <nl> + <nl> + Initializers declared outside of the struct ' s module must always delegate to <nl> + another initializer , since new properties may be added between library releases . <nl> + <nl> + <nl> + Properties <nl> + mmmmmmmmm - <nl> + <nl> + Struct properties behave largely the same as top - level bindings . They permit <nl> + all of the same modifications , and also allow adding or removing an initial <nl> + value entirely . <nl> + <nl> + Struct properties can also be marked ` ` @ inlineable ` ` , with the same <nl> + restrictions as for top - level bindings . An inlineable stored property may not <nl> + become computed , but the offset of its storage within the struct is not <nl> + necessarily fixed . <nl> + <nl> + . . note : : <nl> + <nl> + One possible layout algorithm would put all inlineable struct constants at <nl> + the start of the struct , sorted by availability , so that the offset * could * <nl> + be fixed . This would have to be balanced against other goals for struct <nl> + layout . <nl> + <nl> + Like top - level constants , it is * not * safe to change a ` ` let ` ` property into a <nl> + variable or vice versa . Properties declared with ` ` let ` ` are assumed not to <nl> + change for the entire lifetime of the program once they have been initialized . <nl> + <nl> + <nl> + Subscripts <nl> + mmmmmmmmm - <nl> + <nl> + Subscripts behave largely the same as properties , except that there are no <nl> + stored subscripts . This means that the following changes are permitted : <nl> + <nl> + - Adding ( but not removing ) a public setter . <nl> + - Adding or removing a non - public , non - versioned setter . <nl> + - Changing the body of an accessor . <nl> + <nl> + Like properties , subscripts can be marked ` ` @ inlineable ` ` , which restricts the <nl> + set of changes : <nl> + <nl> + - Adding versioned setter is still permitted . <nl> + - Adding or removing a non - public , non - versioned setter is still permitted . <nl> + - Changing the body of an accessor is permitted but discouraged ; existing <nl> + clients may use the new implementations , or they may use the implementations <nl> + from the time they were compiled , or a mix of both . <nl> + <nl> + Any inlineable accessors must follow the rules for ` inlineable functions ` _ , <nl> + as described above . <nl> + <nl> + <nl> New Conformances <nl> mmmmmmmmmmmmmmm - <nl> <nl> accommodate new values . More specifically , the following changes are permitted : <nl> cases added in future versions of a library . <nl> <nl> <nl> + Enum Members <nl> + mmmmmmmmmmmm <nl> + <nl> + The rules for enum initializers , methods , and subscripts are identical to those <nl> + for struct members . <nl> + <nl> + <nl> Closed Enums <nl> mmmmmmmmmmmm <nl> <nl> There are very few safe changes to make to protocols : <nl> unconstrained default implementation . <nl> - A new optional requirement may be added to an ` ` @ objc ` ` protocol . <nl> - All members may be reordered , including associated types . <nl> + - Changing * internal * parameter names of function and subscript requirements <nl> + is permitted . <nl> + - Reordering generic requirements is permitted ( but not the generic parameters <nl> + themselves ) . <nl> + - The ` ` @ warn_unused_result ` ` and ` ` @ warn_unqualified_access ` ` attributes may <nl> + be added to a function requirement without any additional versioning <nl> + information . <nl> <nl> All other changes to the protocol itself are forbidden , including : <nl> <nl> Finally , classes allow the following changes that do not apply to structs : <nl> Other than those detailed above , no other changes to a class or its members <nl> are permitted . In particular : <nl> <nl> - - New designated initializers may not be added to a publicly - subclassable <nl> - class . This would change the inheritance of convenience initializers , which <nl> - existing subclasses may depend on . <nl> - - New ` ` required ` ` initializers may not be added to a publicly - subclassable <nl> - class . There is no way to guarantee their presence on existing subclasses . <nl> - ` ` final ` ` may not be added to * or * removed from a class or any of its members . <nl> The presence of ` ` final ` ` enables optimization ; its absence means there may <nl> be subclasses / overrides that would be broken by the change . <nl> are permitted . In particular : <nl> rdar : / / problem / 20829214 <nl> <nl> <nl> + Initializers <nl> + mmmmmmmmmmmm <nl> + <nl> + New designated initializers may not be added to a publicly - subclassable class . <nl> + This would change the inheritance of convenience initializers , which existing <nl> + subclasses may depend on . A publicly - subclassable class also may not change <nl> + a convenience initializer into a designated initializer or vice versa . <nl> + <nl> + Similarly , new ` ` required ` ` initializers may not be added to a <nl> + publicly - subclassable class , including marking an existing initializer <nl> + ` ` required ` ` ; there is no way to guarantee their presence on existing <nl> + subclasses . <nl> + <nl> + All of the modifications permitted for top - level functions are also permitted <nl> + for class initializers . This includes being marked ` ` @ inlineable ` ` , with the <nl> + same restrictions . <nl> + <nl> + <nl> + Methods <nl> + mmmmmm - <nl> + <nl> + Both class and instance methods allow all of the modifications permitted for <nl> + top - level functions , but the potential for overrides complicates things a little . They allow the following changes : <nl> + <nl> + - Changing the body of the method . <nl> + - Changing * internal * parameter names ( i . e . the names used within the method <nl> + body , not the labels that are part of the method ' s full name ) . <nl> + - Reordering generic requirements ( but not the generic parameters themselves ) . <nl> + - Adding a default value to a parameter . <nl> + - Changing or removing a default value is permitted but discouraged ; it may <nl> + break or change the meaning of existing source code . <nl> + - The ` ` @ noreturn ` ` attribute may be added to a public method only if it is <nl> + ` ` final ` ` or the class is not publicly subclassable . ` ` @ noreturn ` ` is a <nl> + ` versioned attribute ` . <nl> + - The ` ` @ warn_unused_result ` ` and ` ` @ warn_unqualified_access ` ` attributes may <nl> + be added to a method without any additional versioning information . <nl> + <nl> + Class and instance methods may be marked ` ` @ inlineable ` ` , with the same <nl> + restrictions as struct methods . ` ` dynamic ` ` methods may not be marked <nl> + ` ` @ inlineable ` ` . <nl> + <nl> + If an inlineable method is overridden , the overriding method does not need to <nl> + also be inlineable . Clients may only inline a method when they can devirtualize <nl> + the call . ( This does permit speculative devirtualization . ) <nl> + <nl> + Any method that overrides a ` ` @ noreturn ` ` method must also be marked <nl> + ` ` @ noreturn ` ` . <nl> + <nl> + <nl> + Properties <nl> + mmmmmmmmm - <nl> + <nl> + Class and instance properties allow * most * of the modifications permitted for <nl> + struct properties , but the potential for overrides complicates things a little . <nl> + Variable properties ( those declared with ` ` var ` ` ) allow the following changes : <nl> + <nl> + - Adding ( but not removing ) a computed setter to a ` ` final ` ` property or a <nl> + property in a non - publicly - subclassable class . <nl> + - Adding or removing a non - public , non - versioned setter . <nl> + - Changing from a stored property to a computed property , or vice versa , as <nl> + long as a previously - versioned setter is not removed . <nl> + - Changing the body of an accessor . <nl> + - Adding or removing an observing accessor ( ` ` willSet ` ` or ` ` didSet ` ` ) to / from <nl> + an existing variable . This is effectively the same as modifying the body of a <nl> + setter . <nl> + - Adding , removing , or changing the initial value of a stored variable . <nl> + - Adding or removing ` ` weak ` ` from a variable with ` ` Optional ` ` type . <nl> + - Adding or removing ` ` unowned ` ` from a variable . <nl> + - Adding or removing ` ` @ NSCopying ` ` to / from a variable . <nl> + <nl> + Adding a public setter to a computed property that may be overridden is <nl> + permitted but discouraged ; any existing overrides will not know what to do with <nl> + the setter and will likely not behave correctly . <nl> + <nl> + Constant properties ( those declared with ` ` let ` ` ) still permit changing their <nl> + value , as well as adding or removing an initial value entirely . <nl> + <nl> + Both variable and constant properties ( on both instances and classes ) may be <nl> + marked ` ` @ inlineable ` ` . This behaves as described for struct properties . <nl> + ` ` dynamic ` ` properties may not be marked ` ` @ inlineable ` ` . <nl> + <nl> + If an inlineable property is overridden , the overriding property does not need <nl> + to also be inlineable . Clients may only inline a property access when they can <nl> + devirtualize it . ( This does permit speculative devirtualization . ) <nl> + <nl> + <nl> + Subscripts <nl> + mmmmmmmmm - <nl> + <nl> + Subscripts behave much like properties ; they inherit the rules of their struct <nl> + counterparts with a few small changes : <nl> + <nl> + - Adding ( but not removing ) a public setter to a ` ` final ` ` subscript or a <nl> + subscript in a non - publicly - subclassable class . <nl> + - Adding or removing a non - public , non - versioned setter . <nl> + - Changing the body of an accessor . <nl> + <nl> + Adding a public setter to a subscript that may be overridden is permitted but <nl> + discouraged ; any existing overrides will not know what to do with the setter <nl> + and will likely not behave correctly . <nl> + <nl> + Class subscripts may be marked ` ` @ inlineable ` ` , which behaves as described for <nl> + struct subscripts . ` ` dynamic ` ` subscripts may not be marked ` ` @ inlineable ` ` . <nl> + <nl> + If an inlineable subscript is overridden , the overriding subscript does not need <nl> + to also be inlineable . Clients may only inline a subscript access when they can <nl> + devirtualize it . ( This does permit speculative devirtualization . ) <nl> + <nl> + <nl> Possible Restrictions on Classes <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> <nl> following changes are permitted : <nl> - Removing any non - public , non - versioned member . <nl> - Changing the body of any methods , initializers , or accessors . <nl> <nl> + . . admonition : : TODO <nl> + <nl> + How does " adding any new member " square with the restrictions on adding <nl> + initializers to classes ? Are they inherently convenience initializers ? <nl> + <nl> + What about everything else ? New members in protocols can result in new <nl> + overrideable members in classes . How does that work ? <nl> + <nl> <nl> Operators <nl> ~ ~ ~ ~ ~ ~ ~ ~ ~ <nl>
[ docs ] LibraryEvolution : Discuss nominal members explicitly .
apple/swift
6e4599ca01010a1d30e90abc17f872bee897f197
2016-02-06T04:48:15Z
mmm a / README . md <nl> ppp b / README . md <nl> Arduino core for ESP8266 WiFi chip <nl> <nl> # Quick links <nl> <nl> - - [ Latest release documentation ] ( https : / / arduino - esp8266 . readthedocs . io / en / 2 . 6 . 0 / ) <nl> + - [ Latest release documentation ] ( https : / / arduino - esp8266 . readthedocs . io / en / 2 . 6 . 1 / ) <nl> - [ Current " git version " documentation ] ( https : / / arduino - esp8266 . readthedocs . io / en / latest / ) <nl> - [ Install git version ] ( https : / / arduino - esp8266 . readthedocs . io / en / latest / installing . html # using - git - version ) ( [ sources ] ( doc / installing . rst # using - git - version ) ) <nl> <nl> Starting with 1 . 6 . 4 , Arduino allows installation of third - party platform package <nl> # # # # Latest release [ ! [ Latest release ] ( https : / / img . shields . io / github / release / esp8266 / Arduino . svg ) ] ( https : / / github . com / esp8266 / Arduino / releases / latest / ) <nl> Boards manager link : ` https : / / arduino . esp8266 . com / stable / package_esp8266com_index . json ` <nl> <nl> - Documentation : [ https : / / arduino - esp8266 . readthedocs . io / en / 2 . 6 . 0 / ] ( https : / / arduino - esp8266 . readthedocs . io / en / 2 . 6 . 0 / ) <nl> + Documentation : [ https : / / arduino - esp8266 . readthedocs . io / en / 2 . 6 . 1 / ] ( https : / / arduino - esp8266 . readthedocs . io / en / 2 . 6 . 1 / ) <nl> <nl> # # # Using git version <nl> [ ! [ Linux build status ] ( https : / / travis - ci . org / esp8266 / Arduino . svg ) ] ( https : / / travis - ci . org / esp8266 / Arduino ) <nl> mmm a / platform . txt <nl> ppp b / platform . txt <nl> <nl> # For more info : <nl> # https : / / github . com / arduino / Arduino / wiki / Arduino - IDE - 1 . 5 - 3rd - party - Hardware - specification <nl> <nl> - name = ESP8266 Boards ( 2 . 6 . 1 ) <nl> - version = 2 . 6 . 1 <nl> + name = ESP8266 Boards ( 2 . 7 . 0 - dev ) <nl> + version = 2 . 7 . 0 - dev <nl> <nl> # These will be removed by the packager script when doing a JSON release <nl> runtime . tools . xtensa - lx106 - elf - gcc . path = { runtime . platform . path } / tools / xtensa - lx106 - elf <nl>
Update platform to 2 . 7 . 0 - dev , bump Readme to 2 . 6 . 1 ( )
esp8266/Arduino
48ea3a3e9edd0922ef70d859542240422698b778
2019-11-14T16:36:32Z
mmm a / Source / Math / CuDnnConvolutionEngine . cu <nl> ppp b / Source / Math / CuDnnConvolutionEngine . cu <nl> bool CuDnnConvolutionEngineFactory < ElemType > : : IsSupported ( DEVICEID_TYPE deviceId <nl> / / detect asymmetric padding ( either by auto - padding or by specifying lowerPad / upperPad ) and choose <nl> / / the reference convolution implementation instead <nl> const auto & autopad = geometry - > AutoPad ( ) ; <nl> + assert ( autopad . size ( ) = = kernelRank ) ; <nl> const auto & lowerpad = geometry - > LowerPad ( ) ; <nl> - const auto & upperpad = geometry - > UpperPad ( ) ; <nl> + const auto & upperpad = geometry - > UpperPad ( ) ; <nl> + const auto & padRank = min ( lowerpad . GetRank ( ) , upperpad . GetRank ( ) ) ; / / there are cases where padRank < kernelRank <nl> for ( int i = 0 ; i < kernelRank ; i + + ) <nl> { <nl> if ( autopad [ i ] ) <nl> retVal = retVal & & ( kernel [ i ] % 2 ! = 0 ) ; / / make sure kernel size is odd <nl> - else <nl> + else if ( i < padRank ) <nl> retVal = retVal & & ( lowerpad [ i ] = = upperpad [ i ] ) ; / / make sure lower and upper padding are equal <nl> } <nl> - return retVal ; <nl> + return retVal ; <nl> } <nl> <nl> template class CuDnnConvolutionEngineFactory < float > ; <nl>
Bug fix when lowerPad and upperPad has lower ranks than kernelPad .
microsoft/CNTK
02291c55b4b868236a57dc3b6b230001bf55e498
2017-01-05T00:26:33Z
mmm a / src / MainWindow . cpp <nl> ppp b / src / MainWindow . cpp <nl> <nl> <nl> # include < limits > <nl> <nl> - const int MainWindow : : MaxRecentFiles ; <nl> + int MainWindow : : MaxRecentFiles ; <nl> <nl> MainWindow : : MainWindow ( QWidget * parent ) <nl> : QMainWindow ( parent ) , <nl> void MainWindow : : init ( ) <nl> QShortcut * shortcutFocusEditor = new QShortcut ( QKeySequence ( tr ( " Ctrl + PgUp " ) ) , ui - > tabSqlAreas , nullptr , nullptr , Qt : : WidgetWithChildrenShortcut ) ; <nl> connect ( shortcutFocusEditor , & QShortcut : : activated , this , & MainWindow : : focusSqlEditor ) ; <nl> <nl> + / / Get MaxRecentFiles value from QSettings . <nl> + MaxRecentFiles = Settings : : getValue ( " General " , " maxRecentFiles " ) . toInt ( ) ; <nl> + recentFileActs . resize ( MaxRecentFiles ) ; <nl> + <nl> / / Create the actions for the recently opened dbs list <nl> for ( int i = 0 ; i < MaxRecentFiles ; + + i ) { <nl> recentFileActs [ i ] = new QAction ( this ) ; <nl> void MainWindow : : init ( ) <nl> for ( int i = 0 ; i < MaxRecentFiles ; + + i ) <nl> ui - > fileRecentFiles - > insertAction ( ui - > fileExitAction , recentFileActs [ i ] ) ; <nl> <nl> - QAction * clearRecentFilesAction = ui - > fileRecentFiles - > addAction ( tr ( " Clear List " ) ) ; <nl> + recentSeparatorAct = ui - > fileRecentFiles - > insertSeparator ( ui - > fileExitAction ) ; <nl> + clearRecentFilesAction = ui - > fileRecentFiles - > addAction ( tr ( " Clear List " ) ) ; <nl> ui - > fileRecentFiles - > insertAction ( ui - > fileExitAction , clearRecentFilesAction ) ; <nl> connect ( clearRecentFilesAction , & QAction : : triggered , this , & MainWindow : : clearRecentFiles ) ; <nl> <nl> void MainWindow : : reloadSettings ( ) <nl> w - > reloadSettings ( ) ; <nl> } <nl> <nl> + / / Set max recent files <nl> + const int newMaxRecentFiles = Settings : : getValue ( " General " , " maxRecentFiles " ) . toInt ( ) ; <nl> + <nl> + if ( MaxRecentFiles < newMaxRecentFiles ) { <nl> + / / If user increase max recent files value . <nl> + ui - > fileRecentFiles - > removeAction ( clearRecentFilesAction ) ; <nl> + <nl> + recentFileActs . resize ( newMaxRecentFiles ) ; <nl> + for ( int i = MaxRecentFiles ; i < newMaxRecentFiles ; + + i ) { <nl> + recentFileActs [ i ] = new QAction ( this ) ; <nl> + recentFileActs [ i ] - > setVisible ( false ) ; <nl> + connect ( recentFileActs [ i ] , & QAction : : triggered , this , & MainWindow : : openRecentFile ) ; <nl> + } <nl> + <nl> + for ( int i = 0 ; i < newMaxRecentFiles ; + + i ) <nl> + ui - > fileRecentFiles - > insertAction ( ui - > fileExitAction , recentFileActs [ i ] ) ; <nl> + <nl> + ui - > fileRecentFiles - > insertSeparator ( ui - > fileExitAction ) ; <nl> + ui - > fileRecentFiles - > insertAction ( ui - > fileExitAction , clearRecentFilesAction ) ; <nl> + <nl> + MaxRecentFiles = newMaxRecentFiles ; <nl> + updateRecentFileActions ( ) ; <nl> + } else if ( MaxRecentFiles > newMaxRecentFiles ) { <nl> + / / If user decrease max recent files value . <nl> + for ( int i = ( MaxRecentFiles - 1 ) ; i > = newMaxRecentFiles ; - - i ) { <nl> + ui - > fileRecentFiles - > removeAction ( recentFileActs [ i ] ) ; <nl> + delete recentFileActs [ i ] ; <nl> + } <nl> + <nl> + recentFileActs . resize ( newMaxRecentFiles ) ; <nl> + MaxRecentFiles = newMaxRecentFiles ; <nl> + updateRecentFileActions ( ) ; <nl> + } <nl> + <nl> switch ( static_cast < Settings : : AppStyle > ( Settings : : getValue ( " General " , " appStyle " ) . toInt ( ) ) ) { <nl> case Settings : : FollowDesktopStyle : <nl> qApp - > setStyleSheet ( " " ) ; <nl> mmm a / src / MainWindow . h <nl> ppp b / src / MainWindow . h <nl> class MainWindow : public QMainWindow <nl> <nl> DbStructureModel * dbStructureModel ; <nl> <nl> - static const int MaxRecentFiles = 5 ; <nl> - QAction * recentFileActs [ MaxRecentFiles ] ; <nl> + static int MaxRecentFiles ; <nl> + QVector < QAction * > recentFileActs ; <nl> + QAction * clearRecentFilesAction ; <nl> + QAction * recentSeparatorAct ; <nl> <nl> EditDialog * editDock ; <nl> PlotDock * plotDock ; <nl> mmm a / src / PreferencesDialog . cpp <nl> ppp b / src / PreferencesDialog . cpp <nl> void PreferencesDialog : : loadSettings ( ) <nl> ui - > toolbarStyleComboSql - > setCurrentIndex ( Settings : : getValue ( " General " , " toolbarStyleSql " ) . toInt ( ) ) ; <nl> ui - > toolbarStyleComboEditCell - > setCurrentIndex ( Settings : : getValue ( " General " , " toolbarStyleEditCell " ) . toInt ( ) ) ; <nl> ui - > spinGeneralFontSize - > setValue ( Settings : : getValue ( " General " , " fontsize " ) . toInt ( ) ) ; <nl> + ui - > spinMaxRecentFiles - > setValue ( Settings : : getValue ( " General " , " maxRecentFiles " ) . toInt ( ) ) ; <nl> } <nl> <nl> void PreferencesDialog : : saveSettings ( ) <nl> void PreferencesDialog : : saveSettings ( ) <nl> Settings : : setValue ( " General " , " toolbarStyleEditCell " , ui - > toolbarStyleComboEditCell - > currentIndex ( ) ) ; <nl> Settings : : setValue ( " General " , " DBFileExtensions " , m_dbFileExtensions . join ( " ; ; " ) ) ; <nl> Settings : : setValue ( " General " , " fontsize " , ui - > spinGeneralFontSize - > value ( ) ) ; <nl> + Settings : : setValue ( " General " , " maxRecentFiles " , ui - > spinMaxRecentFiles - > value ( ) ) ; <nl> <nl> m_proxyDialog - > saveSettings ( ) ; <nl> <nl> mmm a / src / PreferencesDialog . ui <nl> ppp b / src / PreferencesDialog . ui <nl> <nl> < x > 0 < / x > <nl> < y > 0 < / y > <nl> < width > 755 < / width > <nl> - < height > 618 < / height > <nl> + < height > 625 < / height > <nl> < / rect > <nl> < / property > <nl> < property name = " windowTitle " > <nl> <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 4 " column = " 0 " > <nl> + < item row = " 5 " column = " 0 " > <nl> < widget class = " QLabel " name = " labelToolbarStyle " > <nl> < property name = " text " > <nl> < string > Toolbar style < / string > <nl> <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 6 " column = " 1 " > <nl> + < item row = " 7 " column = " 1 " > <nl> < widget class = " QComboBox " name = " toolbarStyleComboMain " > <nl> < property name = " sizePolicy " > <nl> < sizepolicy hsizetype = " Maximum " vsizetype = " Fixed " > <nl> <nl> < / item > <nl> < / widget > <nl> < / item > <nl> - < item row = " 7 " column = " 1 " > <nl> + < item row = " 8 " column = " 1 " > <nl> < widget class = " QComboBox " name = " toolbarStyleComboStructure " > <nl> < property name = " sizePolicy " > <nl> < sizepolicy hsizetype = " Maximum " vsizetype = " Fixed " > <nl> <nl> < / item > <nl> < / widget > <nl> < / item > <nl> - < item row = " 8 " column = " 1 " > <nl> + < item row = " 9 " column = " 1 " > <nl> < widget class = " QComboBox " name = " toolbarStyleComboBrowse " > <nl> < property name = " sizePolicy " > <nl> < sizepolicy hsizetype = " Maximum " vsizetype = " Fixed " > <nl> <nl> < / item > <nl> < / widget > <nl> < / item > <nl> - < item row = " 9 " column = " 1 " > <nl> + < item row = " 10 " column = " 1 " > <nl> < widget class = " QComboBox " name = " toolbarStyleComboSql " > <nl> < property name = " sizePolicy " > <nl> < sizepolicy hsizetype = " Maximum " vsizetype = " Fixed " > <nl> <nl> < / item > <nl> < / widget > <nl> < / item > <nl> - < item row = " 11 " column = " 0 " > <nl> + < item row = " 12 " column = " 0 " > <nl> < widget class = " QLabel " name = " labelUseRemotes " > <nl> < property name = " text " > <nl> < string > Show remote options < / string > <nl> <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 11 " column = " 1 " > <nl> + < item row = " 12 " column = " 1 " > <nl> < widget class = " QCheckBox " name = " checkUseRemotes " > <nl> < property name = " text " > <nl> < string > enabled < / string > <nl> <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 12 " column = " 0 " > <nl> + < item row = " 13 " column = " 0 " > <nl> < widget class = " QLabel " name = " labelUpdates " > <nl> < property name = " text " > <nl> < string > Automatic & amp ; updates < / string > <nl> <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 12 " column = " 1 " > <nl> + < item row = " 13 " column = " 1 " > <nl> < widget class = " QCheckBox " name = " checkUpdates " > <nl> < property name = " text " > <nl> < string > enabled < / string > <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 13 " column = " 0 " > <nl> + < item row = " 14 " column = " 0 " > <nl> < widget class = " QLabel " name = " label_16 " > <nl> < property name = " text " > <nl> < string > DB file extensions < / string > <nl> <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 13 " column = " 1 " > <nl> + < item row = " 14 " column = " 1 " > <nl> < widget class = " QPushButton " name = " buttonManageFileExtension " > <nl> < property name = " text " > <nl> < string > Manage < / string > <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 6 " column = " 0 " > <nl> + < item row = " 7 " column = " 0 " > <nl> < widget class = " QLabel " name = " labelMainToolBar " > <nl> < property name = " text " > <nl> < string > Main Window < / string > <nl> <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 7 " column = " 0 " > <nl> + < item row = " 8 " column = " 0 " > <nl> < widget class = " QLabel " name = " labelStructureToolBar " > <nl> < property name = " text " > <nl> < string > Database Structure < / string > <nl> <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 8 " column = " 0 " > <nl> + < item row = " 9 " column = " 0 " > <nl> < widget class = " QLabel " name = " labelBrowseToolBar " > <nl> < property name = " text " > <nl> < string > Browse Data < / string > <nl> <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 9 " column = " 0 " > <nl> + < item row = " 10 " column = " 0 " > <nl> < widget class = " QLabel " name = " labelSqlToolBar " > <nl> < property name = " text " > <nl> < string > Execute SQL < / string > <nl> <nl> < / property > <nl> < / widget > <nl> < / item > <nl> - < item row = " 10 " column = " 1 " > <nl> + < item row = " 11 " column = " 1 " > <nl> < widget class = " QComboBox " name = " toolbarStyleComboEditCell " > <nl> < property name = " sizePolicy " > <nl> < sizepolicy hsizetype = " Maximum " vsizetype = " Fixed " > <nl> <nl> < / item > <nl> < / widget > <nl> < / item > <nl> - < item row = " 10 " column = " 0 " > <nl> + < item row = " 11 " column = " 0 " > <nl> < widget class = " QLabel " name = " labelEditCellToolBar " > <nl> < property name = " text " > <nl> < string > Edit Database Cell < / string > <nl> <nl> < item row = " 3 " column = " 1 " > <nl> < widget class = " QSpinBox " name = " spinGeneralFontSize " / > <nl> < / item > <nl> + < item row = " 4 " column = " 0 " > <nl> + < widget class = " QLabel " name = " labelMaxRecentFiles " > <nl> + < property name = " text " > <nl> + < string > Max Recent Files < / string > <nl> + < / property > <nl> + < / widget > <nl> + < / item > <nl> + < item row = " 4 " column = " 1 " > <nl> + < widget class = " QSpinBox " name = " spinMaxRecentFiles " > <nl> + < property name = " minimum " > <nl> + < number > 1 < / number > <nl> + < / property > <nl> + < property name = " maximum " > <nl> + < number > 40 < / number > <nl> + < / property > <nl> + < / widget > <nl> + < / item > <nl> < / layout > <nl> < / widget > <nl> < widget class = " QWidget " name = " tab " > <nl> mmm a / src / Settings . cpp <nl> ppp b / src / Settings . cpp <nl> QVariant Settings : : getDefaultValue ( const std : : string & group , const std : : string & <nl> if ( group = = " General " & & name = = " recentFileList " ) <nl> return QStringList ( ) ; <nl> <nl> + / / General / maxRecentFiles ? <nl> + if ( group = = " General " & & name = = " maxRecentFiles " ) <nl> + return 5 ; <nl> + <nl> / / General / language ? <nl> if ( group = = " General " & & name = = " language " ) <nl> return QLocale : : system ( ) . name ( ) ; <nl>
Allow the user can change MaxRecentFiles ( )
sqlitebrowser/sqlitebrowser
54ee47b5a9f064dfcb90cd85cf5320d467ef6e12
2020-08-17T17:08:07Z
mmm a / cocos / scripting / lua - bindings / manual / lua_cocos2dx_manual . cpp . REMOVED . git - id <nl> ppp b / cocos / scripting / lua - bindings / manual / lua_cocos2dx_manual . cpp . REMOVED . git - id <nl> @ @ - 1 + 1 @ @ <nl> - 468c9e8472db4be2923ca63484bc72ba2a30ae88 <nl> \ No newline at end of file <nl> + c6021dd4f0d5fbfab61453c2a5f045f4f789a18d <nl> \ No newline at end of file <nl> mmm a / tests / lua - tests / src / CocoStudioTest / CocoStudioGUITest / CocoStudioGUITest . lua . REMOVED . git - id <nl> ppp b / tests / lua - tests / src / CocoStudioTest / CocoStudioGUITest / CocoStudioGUITest . lua . REMOVED . git - id <nl> @ @ - 1 + 1 @ @ <nl> - c43e2d2b4092953dba18fe8223330eb29809bb01 <nl> \ No newline at end of file <nl> + 1f20f88e2a2985963fc6a2d89ea07be41e8e74d0 <nl> \ No newline at end of file <nl>
Merge pull request from samuele3hu / devRichText
cocos2d/cocos2d-x
14ed6e9f5a6d89e1ef53d7976402c8d29d73a17d
2014-04-18T05:55:05Z
mmm a / xbmc / cores / VideoRenderers / LinuxRendererGLES . cpp <nl> ppp b / xbmc / cores / VideoRenderers / LinuxRendererGLES . cpp <nl> void CLinuxRendererGLES : : DeleteYV12Texture ( int index ) <nl> g_graphicsContext . BeginPaint ( ) ; / / FIXME <nl> for ( int f = 0 ; f < MAX_FIELDS ; f + + ) <nl> { <nl> - for ( int p = 0 ; p < 2 ; p + + ) <nl> + for ( int p = 0 ; p < MAX_PLANES ; p + + ) <nl> { <nl> if ( fields [ f ] [ p ] . id ) <nl> { <nl> void CLinuxRendererGLES : : DeleteYV12Texture ( int index ) <nl> fields [ f ] [ p ] . id = 0 ; <nl> } <nl> } <nl> - fields [ f ] [ 2 ] . id = 0 ; <nl> } <nl> g_graphicsContext . EndPaint ( ) ; <nl> <nl> - for ( int p = 0 ; p < 2 ; p + + ) <nl> + for ( int p = 0 ; p < MAX_PLANES ; p + + ) <nl> { <nl> if ( im . plane [ p ] ) <nl> { <nl> bool CLinuxRendererGLES : : CreateYV12Texture ( int index ) <nl> glEnable ( m_textureTarget ) ; <nl> for ( int f = 0 ; f < MAX_FIELDS ; f + + ) <nl> { <nl> - for ( int p = 0 ; p < 2 ; p + + ) <nl> + for ( int p = 0 ; p < MAX_PLANES ; p + + ) <nl> { <nl> if ( ! glIsTexture ( fields [ f ] [ p ] . id ) ) <nl> { <nl> bool CLinuxRendererGLES : : CreateYV12Texture ( int index ) <nl> VerifyGLState ( ) ; <nl> } <nl> } <nl> - fields [ f ] [ 2 ] . id = fields [ f ] [ 1 ] . id ; <nl> } <nl> <nl> / / YUV <nl> bool CLinuxRendererGLES : : CreateYV12Texture ( int index ) <nl> { <nl> planes [ 1 ] . texwidth = planes [ 0 ] . texwidth > > im . cshift_x ; <nl> planes [ 1 ] . texheight = planes [ 0 ] . texheight > > im . cshift_y ; <nl> - planes [ 2 ] . texwidth = planes [ 1 ] . texwidth ; <nl> - planes [ 2 ] . texheight = planes [ 1 ] . texheight ; <nl> + planes [ 2 ] . texwidth = planes [ 0 ] . texwidth > > im . cshift_x ; <nl> + planes [ 2 ] . texheight = planes [ 0 ] . texheight > > im . cshift_y ; <nl> } <nl> <nl> if ( m_renderMethod & RENDER_POT ) <nl>
opps : )
xbmc/xbmc
85dbfe6ebda43db63999e78059b05fec3bbc11bc
2013-10-02T15:25:47Z
mmm a / caffe2 / python / layers / sparse_lookup . py <nl> ppp b / caffe2 / python / layers / sparse_lookup . py <nl> class SparseLookup ( ModelLayer ) : <nl> <nl> def __init__ ( self , model , input_record , inner_shape , reducer , <nl> weight_init = None , weight_optim = None , <nl> - name = ' sparse_lookup ' , regularizer = None , * * kwargs ) : <nl> + name = ' sparse_lookup ' , regularizer = None , use_external_weights = False , * * kwargs ) : <nl> <nl> super ( SparseLookup , self ) . __init__ ( model , name , input_record , * * kwargs ) <nl> <nl> def __init__ ( self , model , input_record , inner_shape , reducer , <nl> <nl> if reducer = = " PositionWeighted " : <nl> assert _is_id_score_list ( self . input_record ) , ( <nl> - " PositionWeighted only support IdScoreList , but got { } for { } " + <nl> - " please use PositionWeighted layer to convert IdList " + <nl> - " to IdScoreList " ) . format ( repr ( self . input_record ) , self . sparse_key ) <nl> + " PositionWeighted only support IdScoreList , but got { } for { } " <nl> + + " please use PositionWeighted layer to convert IdList " <nl> + + " to IdScoreList " <nl> + ) . format ( repr ( self . input_record ) , self . sparse_key ) <nl> self . external_weights = self . input_record . values ( ) <nl> <nl> elif reducer = = " RecencyWeighted " : <nl> assert _is_id_score_list ( self . input_record ) , ( <nl> " RecencyWeighted only supports IdScoreList , " <nl> - " while the sparse feature { } is not . " . format ( self . sparse_key ) ) <nl> + " while the sparse feature { } is not . " . format ( self . sparse_key ) <nl> + ) <nl> + self . external_weights = self . input_record . values ( ) <nl> + # TODO : create a new type of reducer with external weights to wrap <nl> + # this and the above two cases since essentially their input formats <nl> + # are the same . <nl> + elif use_external_weights : <nl> + assert _is_id_score_list ( self . input_record ) , ( <nl> + " Use_external_weights only supports IdScoreList , " <nl> + " while the sparse feature { } is not . " . format ( self . sparse_key ) <nl> + ) <nl> + assert reducer in [ " Sum " , " WeightedSum " ] , ( <nl> + " Use_external_weights only supports Sum reducer , " <nl> + " while the reducer is { } . " . format ( reducer ) <nl> + ) <nl> self . external_weights = self . input_record . values ( ) <nl> self . reducer = reducer <nl> + self . use_external_weights = use_external_weights <nl> <nl> input_dim = get_categorical_limit ( self . input_record ) <nl> - assert input_dim > 0 , ( <nl> - " { } should have categorical limit > 0 , but got { } " . format ( <nl> - self . sparse_key , input_dim ) ) <nl> + assert input_dim > 0 , " { } should have categorical limit > 0 , but got { } " . format ( <nl> + self . sparse_key , input_dim <nl> + ) <nl> <nl> self . input_dim = input_dim <nl> self . shape = [ input_dim ] + inner_shape <nl> def __init__ ( self , model , input_record , inner_shape , reducer , <nl> self . weight_init = weight_init or default_init_op <nl> <nl> self . evicted_values = None <nl> - if schema . equal_schemas ( self . input_record , IdListWithEvicted ) or \ <nl> - schema . equal_schemas ( self . input_record , IdScoreListWithEvicted , <nl> - check_field_types = False ) : <nl> + if schema . equal_schemas ( <nl> + self . input_record , IdListWithEvicted <nl> + ) or schema . equal_schemas ( <nl> + self . input_record , IdScoreListWithEvicted , check_field_types = False <nl> + ) : <nl> self . evicted_values = self . input_record . _evicted_values <nl> <nl> # If fp16 is used , make sure fp16 init op is used <nl> if self . trainer_version = = " fp16 " : <nl> - assert self . reducer in self . _fp16_compatible_reducers , ( <nl> + assert self . reducer in self . _fp16_compatible_reducers or use_external_weights , ( <nl> " Fp16 training is enabled . The reducer specified is not supported . " <nl> " Got { } . Supported reducers : { } . Right now , in general , sum , mean , " <nl> " positional pooling are supported . Attention is not . Please check " <nl> def _gather_wrapper ( self , net , version , in_indices , out ) : <nl> ) <nl> <nl> def _sparse_lengths_weighted_reducer ( <nl> - self , in_indices , weights , reducer , <nl> - net , version , grad_on_weights = 0 ) : <nl> + self , <nl> + in_indices , <nl> + weights , <nl> + reducer , <nl> + net , <nl> + version , <nl> + grad_on_weights = 0 , <nl> + ) : <nl> op_input = [ <nl> self . w , <nl> weights , <nl> in_indices , <nl> - self . input_record . lengths ( ) <nl> + self . input_record . lengths ( ) , <nl> ] <nl> layer_name = ' SparseLengths ' + reducer <nl> <nl> def _add_ops_id_score_list ( self , net , version ) : <nl> self . input_record . values ( ) , <nl> self . reducer , net , version ) <nl> <nl> + elif self . reducer in [ ' PositionWeighted ' , ' RecencyWeighted ' ] or self . use_external_weights : <nl> + self . _sparse_lengths_weighted_reducer ( <nl> + self . input_record . keys ( ) , <nl> + self . external_weights , <nl> + ' WeightedSum ' , net , version , grad_on_weights = 1 ) <nl> + <nl> elif self . reducer in [ ' Sum ' , ' Mean ' ] : <nl> op_input = [ self . w , <nl> self . input_record . keys ( ) , <nl> def _add_ops_id_score_list ( self , net , version ) : <nl> version , self . sparse_key <nl> ) <nl> <nl> - elif self . reducer in [ ' PositionWeighted ' , ' RecencyWeighted ' ] : <nl> - self . _sparse_lengths_weighted_reducer ( <nl> - self . input_record . keys ( ) , <nl> - self . external_weights , <nl> - ' WeightedSum ' , net , version , grad_on_weights = 1 ) <nl> - <nl> elif self . reducer = = ' None ' : <nl> # Gather operator will gather the embedding for each id of <nl> # each IdList . <nl> mmm a / caffe2 / python / layers_test . py <nl> ppp b / caffe2 / python / layers_test . py <nl> def old_get_sparse_key_logic ( input_record ) : <nl> get_key ( id_list_record ) ( ) , <nl> old_get_sparse_key_logic ( id_list_record ) <nl> ) <nl> + <nl> + def testSparseLookupWithAttentionWeightOnIdScoreList ( self ) : <nl> + record = schema . NewRecord ( <nl> + self . model . net , <nl> + schema . Map ( <nl> + schema . Scalar ( <nl> + np . int64 , <nl> + metadata = schema . Metadata ( categorical_limit = 1000 ) , <nl> + ) , <nl> + np . float32 , <nl> + ) , <nl> + ) <nl> + embedding_dim = 64 <nl> + embedding_after_pooling = self . model . SparseLookup ( <nl> + record , [ embedding_dim ] , " Sum " , use_external_weights = True <nl> + ) <nl> + self . model . output_schema = schema . Struct ( ) <nl> + self . assertEqual ( <nl> + schema . Scalar ( ( np . float32 , ( embedding_dim , ) ) ) , embedding_after_pooling <nl> + ) <nl> + <nl> + train_init_net , train_net = self . get_training_nets ( ) <nl> + <nl> + init_ops = self . assertNetContainOps ( <nl> + train_init_net , <nl> + [ OpSpec ( " UniformFill " , None , None ) , OpSpec ( " ConstantFill " , None , None ) ] , <nl> + ) <nl> + sparse_lookup_op_spec = OpSpec ( <nl> + " SparseLengthsWeightedSum " , <nl> + [ <nl> + init_ops [ 0 ] . output [ 0 ] , <nl> + record . values ( ) , <nl> + record . keys ( ) , <nl> + record . lengths ( ) , <nl> + ] , <nl> + [ embedding_after_pooling ( ) ] , <nl> + ) <nl> + self . assertNetContainOps ( train_net , [ sparse_lookup_op_spec ] ) <nl> + <nl> + predict_net = self . get_predict_net ( ) <nl> + self . assertNetContainOps ( predict_net , [ sparse_lookup_op_spec ] ) <nl>
Add support for attention weight in SparseLookup ( )
pytorch/pytorch
1f158adeee296d7287a49f95f16a06361993ef34
2019-10-09T03:22:25Z
mmm a / modules / python / src2 / cv2 . cpp <nl> ppp b / modules / python / src2 / cv2 . cpp <nl> PyObject * pyopencv_from ( const Point2d & p ) <nl> template < > <nl> PyObject * pyopencv_from ( const Point3d & p ) <nl> { <nl> - return Py_BuildValue ( " ( ddd ) " , p . x , p . y , p . y ) ; <nl> + return Py_BuildValue ( " ( ddd ) " , p . x , p . y , p . z ) ; <nl> } <nl> <nl> template < typename _Tp > struct pyopencvVecConverter <nl>
Merge pull request from wpalfi : patch - 1
opencv/opencv
0d86681b88d4605b49ea06e0e6218c1bcc36925c
2017-05-30T20:11:33Z
mmm a / include / swift / Frontend / DiagnosticVerifier . h <nl> ppp b / include / swift / Frontend / DiagnosticVerifier . h <nl> <nl> # ifndef SWIFT_FRONTEND_DIAGNOSTIC_VERIFIER_H <nl> # define SWIFT_FRONTEND_DIAGNOSTIC_VERIFIER_H <nl> <nl> + # include " llvm / ADT / SmallString . h " <nl> # include " swift / AST / DiagnosticConsumer . h " <nl> # include " swift / Basic / LLVM . h " <nl> <nl>
Add a missing header .
apple/swift
828b97953b8fde0c5e24380288d6ec80cc9ca225
2020-03-31T08:04:25Z
mmm a / docs - translations / ko - KR / README . md <nl> ppp b / docs - translations / ko - KR / README . md <nl> GitHub 프로젝트내에서만 볼 수 있고 ` master ` 브랜치의 문서는 <nl> * [ 개요 ] ( api / synopsis . md ) <nl> * [ Process 객체 ] ( api / process . md ) <nl> * [ 크롬 명령줄 스위치 지원 ] ( api / chrome - command - line - switches . md ) <nl> + * [ 환경 변수 ] ( api / environment - variables . md ) <nl> <nl> # # # 커스텀 DOM elements : <nl> <nl> mmm a / docs - translations / ko - KR / api / app . md <nl> ppp b / docs - translations / ko - KR / api / app . md <nl> Returns : <nl> <nl> 어플리케이션이 종료될 때 발생하는 이벤트입니다 . <nl> <nl> - # # # Event : ' open - file ' <nl> + # # # Event : ' open - file ' _OS X_ <nl> <nl> Returns : <nl> <nl> Returns : <nl> <nl> 이 이벤트를 처리할 땐 반드시 ` event . preventDefault ( ) ` 를 호출해야 합니다 . <nl> <nl> - # # # Event : ' open - url ' <nl> + Windows에선 ` process . argv ` 를 통해 파일 경로를 얻을 수 있습니다 . <nl> + <nl> + # # # Event : ' open - url ' _OS X_ <nl> <nl> Returns : <nl> <nl> new file mode 100644 <nl> index 000000000000 . . 11d350692161 <nl> mmm / dev / null <nl> ppp b / docs - translations / ko - KR / api / environment - variables . md <nl> <nl> + # 환경 변수 <nl> + <nl> + Electron의 몇몇 동작은 명령 줄과 어플리케이션의 코드보다 먼저 초기화되어야 하므로 환경 변수에 의해 작동합니다 . <nl> + <nl> + POSIX 쉘의 예시입니다 : <nl> + <nl> + ` ` ` bash <nl> + $ export ELECTRON_ENABLE_LOGGING = true <nl> + $ electron <nl> + ` ` ` <nl> + <nl> + Windows 콘솔의 예시입니다 : <nl> + <nl> + ` ` ` powershell <nl> + > set ELECTRON_ENABLE_LOGGING = true <nl> + > electron <nl> + ` ` ` <nl> + <nl> + # # ` ELECTRON_RUN_AS_NODE ` <nl> + <nl> + 프로세스를 일반 Node . js 프로세스처럼 시작합니다 . ( electron 모듈 제외 ) <nl> + <nl> + # # ` ELECTRON_ENABLE_LOGGING ` <nl> + <nl> + Chrome의 내부 로그를 콘솔에 출력합니다 . <nl> + <nl> + # # ` ELECTRON_ENABLE_STACK_DUMPING ` <nl> + <nl> + Electron이 크래시되면 , 콘솔에 stack trace를 출력합니다 . <nl> + <nl> + 이 환경 변수는 ` crashReporter ` 가 시작되지 않았을 경우 작동하지 않습니다 . <nl> + <nl> + # # ` ELECTRON_DEFAULT_ERROR_MODE ` _Windows_ <nl> + <nl> + Electron이 크래시되면 , 크래시 정보 창을 표시합니다 . <nl> + <nl> + 이 환경 변수는 ` crashReporter ` 가 시작되지 않았을 경우 작동하지 않습니다 . <nl> + <nl> + # # ` ELECTRON_NO_ATTACH_CONSOLE ` _Windows_ <nl> + <nl> + 현재 콘솔 세션에 소속시키지 않습니다 . <nl> + <nl> + # # ` ELECTRON_FORCE_WINDOW_MENU_BAR ` _Linux_ <nl> + <nl> + Linux의 글로벌 메뉴 막대를 사용하지 않습니다 . <nl> + <nl> + # # ` ELECTRON_HIDE_INTERNAL_MODULES ` <nl> + <nl> + ` require ( ' ipc ' ) ` 같은 예전 방식의 빌트인 모듈을 비활성화합니다 . <nl>
Merge pull request from preco21 / master
electron/electron
628ee93b0b04c410e7a452f6f2b4a3d3f3f4bf5b
2015-11-27T10:38:13Z
mmm a / tensorflow / contrib / data / python / kernel_tests / dataset_constructor_op_test . py <nl> ppp b / tensorflow / contrib / data / python / kernel_tests / dataset_constructor_op_test . py <nl> <nl> import numpy as np <nl> <nl> from tensorflow . contrib . data . python . ops import dataset_ops <nl> + from tensorflow . core . protobuf import config_pb2 <nl> + from tensorflow . python . client import session <nl> from tensorflow . python . framework import dtypes <nl> from tensorflow . python . framework import errors <nl> + from tensorflow . python . framework import ops <nl> from tensorflow . python . framework import sparse_tensor <nl> from tensorflow . python . ops import array_ops <nl> from tensorflow . python . ops import math_ops <nl> + from tensorflow . python . ops import resource_variable_ops <nl> from tensorflow . python . platform import test <nl> from tensorflow . python . util import nest <nl> <nl> def generator ( ) : <nl> with self . assertRaises ( errors . OutOfRangeError ) : <nl> sess . run ( get_next ) <nl> <nl> + def testSplitPipelineFailsWithPlacementError ( self ) : <nl> + <nl> + with session . Session ( <nl> + target = " " , <nl> + config = config_pb2 . ConfigProto ( device_count = { " CPU " : 2 } ) ) as sess : <nl> + <nl> + dataset = dataset_ops . Dataset . from_tensors ( 0 ) <nl> + <nl> + # Define a pipeline that attempts to use variables on two <nl> + # different devices . <nl> + # <nl> + # Initialize the variables before creating to iterator , to avoid the <nl> + # placement algorithm overriding the DT_RESOURCE colocation constraints . <nl> + with ops . device ( " / cpu : 0 " ) : <nl> + var_0 = resource_variable_ops . ResourceVariable ( initial_value = 0 ) <nl> + dataset = dataset . map ( lambda x : x + var_0 . read_value ( ) ) <nl> + sess . run ( var_0 . initializer ) <nl> + <nl> + with ops . device ( " / cpu : 1 " ) : <nl> + var_1 = resource_variable_ops . ResourceVariable ( initial_value = 0 ) <nl> + dataset = dataset . map ( lambda x : x + var_1 . read_value ( ) ) <nl> + sess . run ( var_1 . initializer ) <nl> + <nl> + iterator = dataset . make_initializable_iterator ( ) <nl> + <nl> + with self . assertRaisesRegexp ( <nl> + errors . InvalidArgumentError , <nl> + " Trying to access resource located in device " ) : <nl> + sess . run ( iterator . initializer ) <nl> <nl> if __name__ = = " __main__ " : <nl> test . main ( ) <nl> mmm a / tensorflow / contrib / data / python / kernel_tests / resample_test . py <nl> ppp b / tensorflow / contrib / data / python / kernel_tests / resample_test . py <nl> <nl> <nl> from tensorflow . contrib . data . python . ops import dataset_ops <nl> from tensorflow . python . framework import errors <nl> + from tensorflow . python . framework import ops <nl> from tensorflow . python . ops import string_ops <nl> from tensorflow . python . ops import variables <nl> from tensorflow . python . platform import test <nl> + from tensorflow . python . training import device_setter <nl> from tensorflow . python . util import compat <nl> <nl> <nl> def _testDistribution ( self , initial_known ) : <nl> seed = 27 ) ) <nl> init_op = iterator . initializer <nl> get_next = iterator . get_next ( ) <nl> - variable_init_op = variables . global_variables_initializer ( ) <nl> + variable_init_op = variables . local_variables_initializer ( ) <nl> <nl> with self . test_session ( ) as sess : <nl> sess . run ( variable_init_op ) <nl> def _testDistribution ( self , initial_known ) : <nl> returned_dist = class_counts / total_returned <nl> self . assertAllClose ( target_dist , returned_dist , atol = 1e - 2 ) <nl> <nl> + def testVariableDevicePlacement ( self ) : <nl> + classes = np . random . randint ( 5 , size = ( 20000 , ) ) # Uniformly sampled <nl> + target_dist = [ 0 . 9 , 0 . 05 , 0 . 05 , 0 . 0 , 0 . 0 ] <nl> + with ops . device ( <nl> + device_setter . replica_device_setter ( ps_tasks = 1 , ps_device = " / cpu : 0 " ) ) : <nl> + dataset = ( dataset_ops . Dataset . from_tensor_slices ( classes ) <nl> + . shuffle ( 200 , seed = 21 ) <nl> + . map ( lambda c : ( c , string_ops . as_string ( c ) ) ) ) <nl> + dataset = dataset_ops . rejection_resample ( <nl> + dataset , target_dist = target_dist , initial_dist = None , <nl> + class_func = lambda c , _ : c , seed = 27 ) <nl> + <nl> + self . assertEqual ( 1 , len ( variables . local_variables ( ) ) ) <nl> + self . assertEqual ( b " " , <nl> + compat . as_bytes ( variables . local_variables ( ) [ 0 ] . device ) ) <nl> + <nl> <nl> if __name__ = = " __main__ " : <nl> test . main ( ) <nl> mmm a / tensorflow / contrib / data / python / ops / dataset_ops . py <nl> ppp b / tensorflow / contrib / data / python / ops / dataset_ops . py <nl> def from_dataset ( dataset , shared_name = None ) : <nl> shared_name = shared_name , <nl> output_types = nest . flatten ( dataset . output_types ) , <nl> output_shapes = nest . flatten ( dataset . output_shapes ) ) <nl> - initializer = gen_dataset_ops . make_iterator ( dataset . make_dataset_resource ( ) , <nl> - iterator_resource ) <nl> + with ops . colocate_with ( iterator_resource ) : <nl> + initializer = gen_dataset_ops . make_iterator ( <nl> + dataset . make_dataset_resource ( ) , iterator_resource ) <nl> return Iterator ( iterator_resource , initializer , dataset . output_types , <nl> dataset . output_shapes ) <nl> <nl> def make_initializer ( self , dataset , name = None ) : <nl> raise TypeError ( " Expected output shapes compatible with % r but got " <nl> " dataset with output shapes % r . " % <nl> ( self . _output_shapes , dataset . output_shapes ) ) <nl> + with ops . colocate_with ( self . _iterator_resource ) : <nl> return gen_dataset_ops . make_iterator ( <nl> dataset . make_dataset_resource ( ) , self . _iterator_resource , name = name ) <nl> <nl> def rejection_resample ( dataset , <nl> num_classes = ( target_dist . shape [ 0 ] . value or <nl> array_ops . shape ( target_dist ) [ 0 ] ) <nl> smoothing_constant = 10 <nl> - num_examples_per_class_seen = resource_variable_ops . ResourceVariable ( <nl> - initial_value = array_ops . fill ( [ num_classes ] , <nl> - np . int64 ( smoothing_constant ) ) , <nl> - trainable = False , <nl> - name = " class_count " , <nl> - dtype = dtypes . int64 ) <nl> + # Disable device functions and colocation constraints so that the variable <nl> + # will be placed with the eventual DT_VARIANT dataset tensor . <nl> + with ops . colocate_with ( None , ignore_existing = True ) : <nl> + num_examples_per_class_seen = resource_variable_ops . ResourceVariable ( <nl> + initial_value = array_ops . fill ( [ num_classes ] , <nl> + np . int64 ( smoothing_constant ) ) , <nl> + trainable = False , <nl> + collections = [ ops . GraphKeys . LOCAL_VARIABLES ] , <nl> + name = " local_class_count " , <nl> + dtype = dtypes . int64 ) <nl> <nl> def update_estimate_and_tile ( c ) : <nl> return array_ops . tile ( <nl>
[ tf . contrib . data ] Add colocation constraints between Iterator and Datasets .
tensorflow/tensorflow
6d51dd66d1fd938fa0f95f5933169aaccd6aef76
2017-09-15T15:59:11Z
mmm a / src / buffer_cache / mirrored / patch_disk_storage . cc <nl> ppp b / src / buffer_cache / mirrored / patch_disk_storage . cc <nl> void patch_disk_storage_t : : init ( const block_id_t first_block , const block_id_t n <nl> if ( number_of_blocks = = 0 ) <nl> return ; <nl> <nl> - / / TODO : Make this parallel maybe to speed up database loading on HDD ? ( but would that even help ? ) <nl> + / / Preload blocks into memory <nl> + coro_t : : move_to_thread ( cache . serializer - > home_thread ) ; <nl> + for ( block_id_t current_block = first_block ; current_block < first_block + number_of_blocks ; + + current_block ) { <nl> + bool block_in_use = cache . serializer - > block_in_use ( current_block ) ; <nl> + if ( block_in_use ) { <nl> + coro_t : : spawn ( boost : : bind ( & patch_disk_storage_t : : preload_block , this , current_block ) ) ; <nl> + } <nl> + } <nl> + coro_t : : move_to_thread ( cache . home_thread ) ; <nl> <nl> / / Load all log blocks into memory <nl> for ( block_id_t current_block = first_block ; current_block < first_block + number_of_blocks ; + + current_block ) { <nl> void patch_disk_storage_t : : init ( const block_id_t first_block , const block_id_t n <nl> void * buf_data = log_buf - > get_data_major_write ( ) ; <nl> guarantee ( strncmp ( ( char * ) buf_data , LOG_BLOCK_MAGIC , sizeof ( LOG_BLOCK_MAGIC ) ) = = 0 ) ; <nl> } else { <nl> - / / Initialize a new log block here ( we rely on the property block_id assignment properties ) <nl> + / / Initialize a new log block here ( we rely on the properties of block_id assignment ) <nl> mc_inner_buf_t * new_ibuf = new mc_inner_buf_t ( & cache ) ; <nl> guarantee ( new_ibuf - > block_id = = current_block ) ; <nl> <nl> void patch_disk_storage_t : : compress_block ( const block_id_t log_block_id ) { <nl> } <nl> } <nl> <nl> + void patch_disk_storage_t : : preload_block ( const block_id_t log_block_id ) { <nl> + / / Acquire the block but release it immediately . . . <nl> + coro_t : : move_to_thread ( cache . home_thread ) ; <nl> + acquire_block_no_locking ( log_block_id ) - > release ( ) ; <nl> + coro_t : : move_to_thread ( cache . serializer - > home_thread ) ; <nl> + } <nl> + <nl> void patch_disk_storage_t : : clear_block ( const block_id_t log_block_id , coro_t * notify_coro ) { <nl> cache . assert_thread ( ) ; <nl> <nl> mmm a / src / buffer_cache / mirrored / patch_disk_storage . hpp <nl> ppp b / src / buffer_cache / mirrored / patch_disk_storage . hpp <nl> class patch_disk_storage_t { <nl> void clear_block ( const block_id_t log_block_id , coro_t * notify_coro ) ; <nl> void set_active_log_block ( const block_id_t log_block_id ) ; <nl> <nl> + void preload_block ( const block_id_t log_block_id ) ; <nl> void init_log_block ( const block_id_t log_block_id ) ; <nl> <nl> / / We use our own acquire function which does not care about locks <nl>
Speed up patch log initialization
rethinkdb/rethinkdb
43c2a1f1525ced86b2030afce3094ebbde17c01d
2011-02-25T04:08:49Z
mmm a / folly / Optional . h <nl> ppp b / folly / Optional . h <nl> <nl> <nl> # include < boost / operators . hpp > <nl> <nl> + <nl> namespace folly { <nl> <nl> namespace detail { struct NoneHelper { } ; } <nl> const None none = nullptr ; <nl> # endif / / __GNUC__ <nl> <nl> template < class Value > <nl> - class Optional : boost : : totally_ordered < Optional < Value > , <nl> - boost : : totally_ordered < Optional < Value > , Value > > { <nl> - typedef void ( Optional : : * bool_type ) ( ) const ; <nl> - void truthy ( ) const { } ; <nl> + class Optional { <nl> public : <nl> static_assert ( ! std : : is_reference < Value > : : value , <nl> " Optional may not be used with reference types " ) ; <nl> class Optional : boost : : totally_ordered < Optional < Value > , <nl> } <nl> } <nl> <nl> - / * implicit * / Optional ( const None & empty ) <nl> + / * implicit * / Optional ( const None & ) <nl> : hasValue_ ( false ) { <nl> } <nl> <nl> class Optional : boost : : totally_ordered < Optional < Value > , <nl> return * this ; <nl> } <nl> <nl> - bool operator < ( const Optional & other ) const { <nl> - if ( hasValue ( ) ! = other . hasValue ( ) ) { <nl> - return hasValue ( ) < other . hasValue ( ) ; <nl> - } <nl> - if ( hasValue ( ) ) { <nl> - return value ( ) < other . value ( ) ; <nl> - } <nl> - return false ; / / both empty <nl> - } <nl> - <nl> - bool operator < ( const Value & other ) const { <nl> - return ! hasValue ( ) | | value ( ) < other ; <nl> - } <nl> - <nl> - bool operator = = ( const Optional & other ) const { <nl> - if ( hasValue ( ) ) { <nl> - return other . hasValue ( ) & & value ( ) = = other . value ( ) ; <nl> - } else { <nl> - return ! other . hasValue ( ) ; <nl> - } <nl> - } <nl> - <nl> - bool operator = = ( const Value & other ) const { <nl> - return hasValue ( ) & & value ( ) = = other ; <nl> - } <nl> - <nl> template < class . . . Args > <nl> void emplace ( Args & & . . . args ) { <nl> clear ( ) ; <nl> class Optional : boost : : totally_ordered < Optional < Value > , <nl> <nl> bool hasValue ( ) const { return hasValue_ ; } <nl> <nl> - / * safe bool idiom * / <nl> - operator bool_type ( ) const { <nl> - return hasValue ( ) ? & Optional : : truthy : nullptr ; <nl> + explicit operator bool ( ) const { <nl> + return hasValue ( ) ; <nl> } <nl> <nl> const Value & operator * ( ) const { return value ( ) ; } <nl> Opt make_optional ( T & & v ) { <nl> return Opt ( std : : forward < T > ( v ) ) ; <nl> } <nl> <nl> + template < class V > <nl> + bool operator < ( const Optional < V > & a , const Optional < V > & b ) { <nl> + if ( a . hasValue ( ) ! = b . hasValue ( ) ) { return a . hasValue ( ) < b . hasValue ( ) ; } <nl> + if ( a . hasValue ( ) ) { return a . value ( ) < b . value ( ) ; } <nl> + return false ; <nl> + } <nl> + <nl> + template < class V > <nl> + bool operator = = ( const Optional < V > & a , const Optional < V > & b ) { <nl> + if ( a . hasValue ( ) ! = b . hasValue ( ) ) { return false ; } <nl> + if ( a . hasValue ( ) ) { return a . value ( ) = = b . value ( ) ; } <nl> + return true ; <nl> + } <nl> + <nl> + template < class V > <nl> + bool operator < = ( const Optional < V > & a , const Optional < V > & b ) { <nl> + return ! ( b < a ) ; <nl> + } <nl> + <nl> + template < class V > <nl> + bool operator ! = ( const Optional < V > & a , const Optional < V > & b ) { <nl> + return ! ( b = = a ) ; <nl> + } <nl> + <nl> + template < class V > <nl> + bool operator > = ( const Optional < V > & a , const Optional < V > & b ) { <nl> + return ! ( a < b ) ; <nl> + } <nl> + <nl> + template < class V > <nl> + bool operator > ( const Optional < V > & a , const Optional < V > & b ) { <nl> + return b < a ; <nl> + } <nl> + <nl> + / / To supress comparability of Optional < T > with T , despite implicit conversion . <nl> + template < class V > bool operator < ( const Optional < V > & , const V & other ) = delete ; <nl> + template < class V > bool operator < = ( const Optional < V > & , const V & other ) = delete ; <nl> + template < class V > bool operator = = ( const Optional < V > & , const V & other ) = delete ; <nl> + template < class V > bool operator ! = ( const Optional < V > & , const V & other ) = delete ; <nl> + template < class V > bool operator > = ( const Optional < V > & , const V & other ) = delete ; <nl> + template < class V > bool operator > ( const Optional < V > & , const V & other ) = delete ; <nl> + template < class V > bool operator < ( const V & other , const Optional < V > & ) = delete ; <nl> + template < class V > bool operator < = ( const V & other , const Optional < V > & ) = delete ; <nl> + template < class V > bool operator = = ( const V & other , const Optional < V > & ) = delete ; <nl> + template < class V > bool operator ! = ( const V & other , const Optional < V > & ) = delete ; <nl> + template < class V > bool operator > = ( const V & other , const Optional < V > & ) = delete ; <nl> + template < class V > bool operator > ( const V & other , const Optional < V > & ) = delete ; <nl> + <nl> } / / namespace folly <nl> <nl> # endif / / FOLLY_OPTIONAL_H_ <nl> mmm a / folly / test / OptionalTest . cpp <nl> ppp b / folly / test / OptionalTest . cpp <nl> <nl> # include < gtest / gtest . h > <nl> # include < boost / optional . hpp > <nl> <nl> - using namespace folly ; <nl> using std : : unique_ptr ; <nl> using std : : shared_ptr ; <nl> <nl> + namespace folly { <nl> + <nl> + template < class V > <nl> + std : : ostream & operator < < ( std : : ostream & os , const Optional < V > & v ) { <nl> + if ( v ) { <nl> + os < < " Optional ( " < < v . value ( ) < < ' ) ' ; <nl> + } else { <nl> + os < < " None " ; <nl> + } <nl> + return os ; <nl> + } <nl> + <nl> struct NoDefault { <nl> NoDefault ( int , int ) { } <nl> char a , b , c ; <nl> TEST ( Optional , NoDefault ) { <nl> Optional < NoDefault > x ; <nl> EXPECT_FALSE ( x ) ; <nl> x . emplace ( 4 , 5 ) ; <nl> - EXPECT_TRUE ( x ) ; <nl> + EXPECT_TRUE ( bool ( x ) ) ; <nl> x . clear ( ) ; <nl> EXPECT_FALSE ( x ) ; <nl> } <nl> TEST ( Optional , String ) { <nl> Optional < std : : string > maybeString ; <nl> EXPECT_FALSE ( maybeString ) ; <nl> maybeString = " hello " ; <nl> - EXPECT_TRUE ( maybeString ) ; <nl> + EXPECT_TRUE ( bool ( maybeString ) ) ; <nl> } <nl> <nl> TEST ( Optional , Const ) { <nl> { / / default construct <nl> Optional < const int > opt ; <nl> - EXPECT_FALSE ( opt ) ; <nl> + EXPECT_FALSE ( bool ( opt ) ) ; <nl> opt . emplace ( 4 ) ; <nl> - EXPECT_EQ ( opt , 4 ) ; <nl> + EXPECT_EQ ( * opt , 4 ) ; <nl> opt . emplace ( 5 ) ; <nl> - EXPECT_EQ ( opt , 5 ) ; <nl> + EXPECT_EQ ( * opt , 5 ) ; <nl> opt . clear ( ) ; <nl> - EXPECT_FALSE ( opt ) ; <nl> + EXPECT_FALSE ( bool ( opt ) ) ; <nl> } <nl> { / / copy - constructed <nl> const int x = 6 ; <nl> Optional < const int > opt ( x ) ; <nl> - EXPECT_EQ ( opt , 6 ) ; <nl> + EXPECT_EQ ( * opt , 6 ) ; <nl> } <nl> { / / move - constructed <nl> const int x = 7 ; <nl> Optional < const int > opt ( std : : move ( x ) ) ; <nl> - EXPECT_EQ ( opt , 7 ) ; <nl> + EXPECT_EQ ( * opt , 7 ) ; <nl> } <nl> / / no assignment allowed <nl> } <nl> <nl> TEST ( Optional , Simple ) { <nl> Optional < int > opt ; <nl> - EXPECT_FALSE ( opt ) ; <nl> + EXPECT_FALSE ( bool ( opt ) ) ; <nl> opt = 4 ; <nl> - EXPECT_TRUE ( opt ) ; <nl> + EXPECT_TRUE ( bool ( opt ) ) ; <nl> EXPECT_EQ ( 4 , * opt ) ; <nl> opt = 5 ; <nl> EXPECT_EQ ( 5 , * opt ) ; <nl> opt . clear ( ) ; <nl> - EXPECT_FALSE ( opt ) ; <nl> + EXPECT_FALSE ( bool ( opt ) ) ; <nl> } <nl> <nl> TEST ( Optional , EmptyConstruct ) { <nl> Optional < int > opt ; <nl> - EXPECT_FALSE ( opt ) ; <nl> + EXPECT_FALSE ( bool ( opt ) ) ; <nl> Optional < int > test1 ( opt ) ; <nl> - EXPECT_FALSE ( test1 ) ; <nl> + EXPECT_FALSE ( bool ( test1 ) ) ; <nl> Optional < int > test2 ( std : : move ( opt ) ) ; <nl> - EXPECT_FALSE ( test2 ) ; <nl> + EXPECT_FALSE ( bool ( test2 ) ) ; <nl> } <nl> <nl> TEST ( Optional , Unique ) { <nl> Optional < unique_ptr < int > > opt ; <nl> <nl> opt . clear ( ) ; <nl> - EXPECT_FALSE ( opt ) ; <nl> + EXPECT_FALSE ( bool ( opt ) ) ; <nl> / / empty - > emplaced <nl> opt . emplace ( new int ( 5 ) ) ; <nl> - EXPECT_TRUE ( opt ) ; <nl> + EXPECT_TRUE ( bool ( opt ) ) ; <nl> EXPECT_EQ ( 5 , * * opt ) ; <nl> <nl> opt . clear ( ) ; <nl> TEST ( Optional , Unique ) { <nl> <nl> / / move it out by move construct <nl> Optional < unique_ptr < int > > moved ( std : : move ( opt ) ) ; <nl> - EXPECT_TRUE ( moved ) ; <nl> - EXPECT_FALSE ( opt ) ; <nl> + EXPECT_TRUE ( bool ( moved ) ) ; <nl> + EXPECT_FALSE ( bool ( opt ) ) ; <nl> EXPECT_EQ ( 7 , * * moved ) ; <nl> <nl> - EXPECT_TRUE ( moved ) ; <nl> + EXPECT_TRUE ( bool ( moved ) ) ; <nl> opt = std : : move ( moved ) ; / / move it back by move assign <nl> - EXPECT_FALSE ( moved ) ; <nl> - EXPECT_TRUE ( opt ) ; <nl> + EXPECT_FALSE ( bool ( moved ) ) ; <nl> + EXPECT_TRUE ( bool ( opt ) ) ; <nl> EXPECT_EQ ( 7 , * * opt ) ; <nl> } <nl> <nl> TEST ( Optional , Shared ) { <nl> shared_ptr < int > ptr ; <nl> Optional < shared_ptr < int > > opt ; <nl> - EXPECT_FALSE ( opt ) ; <nl> + EXPECT_FALSE ( bool ( opt ) ) ; <nl> / / empty - > emplaced <nl> opt . emplace ( new int ( 5 ) ) ; <nl> - EXPECT_TRUE ( opt ) ; <nl> + EXPECT_TRUE ( bool ( opt ) ) ; <nl> ptr = opt . value ( ) ; <nl> EXPECT_EQ ( ptr . get ( ) , opt - > get ( ) ) ; <nl> EXPECT_EQ ( 2 , ptr . use_count ( ) ) ; <nl> TEST ( Optional , Order ) { <nl> { 3 } , <nl> } ; <nl> std : : sort ( vect . begin ( ) , vect . end ( ) ) ; <nl> - EXPECT_TRUE ( vect = = expected ) ; <nl> + EXPECT_EQ ( vect , expected ) ; <nl> } <nl> <nl> TEST ( Optional , Swap ) { <nl> TEST ( Optional , Comparisons ) { <nl> Optional < int > o1 ( 1 ) ; <nl> Optional < int > o2 ( 2 ) ; <nl> <nl> - EXPECT_TRUE ( o_ < 1 ) ; <nl> - EXPECT_TRUE ( o_ < = 1 ) ; <nl> EXPECT_TRUE ( o_ < = o_ ) ; <nl> EXPECT_TRUE ( o_ = = o_ ) ; <nl> - EXPECT_TRUE ( o_ ! = 1 ) ; <nl> EXPECT_TRUE ( o_ > = o_ ) ; <nl> - EXPECT_TRUE ( 1 > = o_ ) ; <nl> - EXPECT_TRUE ( 1 > o_ ) ; <nl> <nl> EXPECT_TRUE ( o1 < o2 ) ; <nl> EXPECT_TRUE ( o1 < = o2 ) ; <nl> TEST ( Optional , Comparisons ) { <nl> EXPECT_FALSE ( o1 > = o2 ) ; <nl> EXPECT_FALSE ( o1 > o2 ) ; <nl> <nl> + / * folly : : Optional explicitly doesn ' t support comparisons with contained value <nl> EXPECT_TRUE ( 1 < o2 ) ; <nl> EXPECT_TRUE ( 1 < = o2 ) ; <nl> EXPECT_TRUE ( 1 < = o1 ) ; <nl> TEST ( Optional , Comparisons ) { <nl> EXPECT_FALSE ( o1 > = 2 ) ; <nl> EXPECT_FALSE ( o1 > = 2 ) ; <nl> EXPECT_FALSE ( o1 > 2 ) ; <nl> + * / <nl> + <nl> + / / boost : : optional does support comparison with contained value , which can <nl> + / / lead to confusion when a bool is contained <nl> + boost : : optional < int > boi ( 3 ) ; <nl> + EXPECT_TRUE ( boi < 5 ) ; <nl> + EXPECT_TRUE ( boi < = 4 ) ; <nl> + EXPECT_TRUE ( boi = = 3 ) ; <nl> + EXPECT_TRUE ( boi ! = 2 ) ; <nl> + EXPECT_TRUE ( boi > = 1 ) ; <nl> + EXPECT_TRUE ( boi > 0 ) ; <nl> + EXPECT_TRUE ( 1 < boi ) ; <nl> + EXPECT_TRUE ( 2 < = boi ) ; <nl> + EXPECT_TRUE ( 3 = = boi ) ; <nl> + EXPECT_TRUE ( 4 ! = boi ) ; <nl> + EXPECT_TRUE ( 5 > = boi ) ; <nl> + EXPECT_TRUE ( 6 > boi ) ; <nl> + <nl> + boost : : optional < bool > bob ( false ) ; <nl> + EXPECT_TRUE ( bob ) ; <nl> + EXPECT_TRUE ( bob = = false ) ; / / well that was confusing <nl> + EXPECT_FALSE ( bob ! = false ) ; <nl> + } <nl> + <nl> + TEST ( Optional , Conversions ) { <nl> + Optional < bool > mbool ; <nl> + Optional < short > mshort ; <nl> + Optional < char * > mstr ; <nl> + Optional < int > mint ; <nl> + <nl> + / / These don ' t compile <nl> + / / bool b = mbool ; <nl> + / / short s = mshort ; <nl> + / / char * c = mstr ; <nl> + / / int x = mint ; <nl> + / / char * c ( mstr ) ; <nl> + / / short s ( mshort ) ; <nl> + / / int x ( mint ) ; <nl> + <nl> + / / intended explicit operator bool , for if ( opt ) . <nl> + bool b ( mbool ) ; <nl> + <nl> + / / Truthy tests work and are not ambiguous <nl> + if ( mbool & & mshort & & mstr & & mint ) { / / only checks not - empty <nl> + if ( * mbool & & * mshort & & * mstr & & * mint ) { / / only checks value <nl> + ; <nl> + } <nl> + } <nl> + <nl> + mbool = false ; <nl> + EXPECT_TRUE ( bool ( mbool ) ) ; <nl> + EXPECT_FALSE ( * mbool ) ; <nl> + <nl> + mbool = true ; <nl> + EXPECT_TRUE ( bool ( mbool ) ) ; <nl> + EXPECT_TRUE ( * mbool ) ; <nl> + <nl> + mbool = none ; <nl> + EXPECT_FALSE ( bool ( mbool ) ) ; <nl> + <nl> + / / No conversion allowed ; does not compile <nl> + / / EXPECT_TRUE ( mbool = = false ) ; <nl> } <nl> <nl> TEST ( Optional , Pointee ) { <nl> TEST ( Optional , Pointee ) { <nl> x = 1 ; <nl> EXPECT_TRUE ( get_pointer ( x ) ) ; <nl> * get_pointer ( x ) = 2 ; <nl> - EXPECT_TRUE ( x = = 2 ) ; <nl> + EXPECT_TRUE ( * x = = 2 ) ; <nl> x = none ; <nl> EXPECT_FALSE ( get_pointer ( x ) ) ; <nl> } <nl> TEST ( Optional , AssignmentContained ) { <nl> EXPECT_FALSE ( target . hasValue ( ) ) ; <nl> } <nl> } <nl> + <nl> + } <nl>
Disabling conversion with contained value for Optional
facebook/folly
5f517beb049f122c268c3b5bf2eb747b5e7b3a7b
2013-05-20T18:01:26Z
mmm a / src / mongo / db / repl / rs_config . h <nl> ppp b / src / mongo / db / repl / rs_config . h <nl> namespace mongo { <nl> <nl> return _id = = r . _id & & votes = = r . votes & & h = = r . h & & priority = = r . priority & & <nl> arbiterOnly = = r . arbiterOnly & & slaveDelay = = r . slaveDelay & & hidden = = r . hidden & & <nl> - buildIndexes = = buildIndexes ; <nl> + buildIndexes = = r . buildIndexes ; <nl> } <nl> bool operator ! = ( const MemberCfg & r ) const { return ! ( * this = = r ) ; } <nl> } ; <nl>
SERVER - 6060 : Fix comparison operator ReplSetConfig : : operator = = .
mongodb/mongo
39031a8d3909b1d85b45b60655cb1dd7c226ad96
2012-06-13T20:30:09Z
mmm a / modules / nonfree / src / surf . ocl . cpp <nl> ppp b / modules / nonfree / src / surf . ocl . cpp <nl> namespace cv <nl> <nl> size_t wave_size = 0 ; <nl> queryDeviceInfo ( WAVEFRONT_SIZE , & wave_size ) ; <nl> - std : : sprintf ( pSURF_OPTIONS , " - D WAVE_SIZE = % d " , static_cast < int > ( wave_size ) ) ; <nl> + std : : sprintf ( pSURF_OPTIONS , " - D WAVE_SIZE = % d " , static_cast < int > ( wave_size ) ) ; <nl> OPTION_INIT = true ; <nl> } <nl> openCLExecuteKernel ( clCxt , source , kernelName , globalThreads , localThreads , args , channels , depth , SURF_OPTIONS ) ; <nl> mmm a / modules / ocl / src / filtering . cpp <nl> ppp b / modules / ocl / src / filtering . cpp <nl> static void GPUErode ( const oclMat & src , oclMat & dst , oclMat & mat_kernel , <nl> char compile_option [ 128 ] ; <nl> sprintf ( compile_option , " - D RADIUSX = % d - D RADIUSY = % d - D LSIZE0 = % d - D LSIZE1 = % d - D ERODE % s % s " , <nl> anchor . x , anchor . y , ( int ) localThreads [ 0 ] , ( int ) localThreads [ 1 ] , <nl> - rectKernel ? " - D RECTKERNEL " : " " , <nl> - s ) ; <nl> + s , rectKernel ? " - D RECTKERNEL " : " " ) ; <nl> vector < pair < size_t , const void * > > args ; <nl> args . push_back ( make_pair ( sizeof ( cl_mem ) , ( void * ) & src . data ) ) ; <nl> args . push_back ( make_pair ( sizeof ( cl_mem ) , ( void * ) & dst . data ) ) ; <nl> mmm a / modules / ocl / src / opencl / arithm_flip . cl <nl> ppp b / modules / ocl / src / opencl / arithm_flip . cl <nl> __kernel void arithm_flip_cols_C1_D0 ( __global uchar * src , int src_step , int src <nl> if ( x < thread_cols & & y < rows ) <nl> { <nl> int src_index_0 = mad24 ( y , src_step , ( x ) + src_offset ) ; <nl> - int src_index_1 = mad24 ( y , src_step , ( cols - x - 1 ) + src_offset ) ; <nl> - <nl> - int dst_index_0 = mad24 ( y , dst_step , ( x ) + dst_offset ) ; <nl> int dst_index_1 = mad24 ( y , dst_step , ( cols - x - 1 ) + dst_offset ) ; <nl> - <nl> uchar data0 = * ( src + src_index_0 ) ; <nl> - uchar data1 = * ( src + src_index_1 ) ; <nl> + * ( dst + dst_index_1 ) = data0 ; <nl> <nl> + int src_index_1 = mad24 ( y , src_step , ( cols - x - 1 ) + src_offset ) ; <nl> + int dst_index_0 = mad24 ( y , dst_step , ( x ) + dst_offset ) ; <nl> + uchar data1 = * ( src + src_index_1 ) ; <nl> * ( dst + dst_index_0 ) = data1 ; <nl> - * ( dst + dst_index_1 ) = data0 ; <nl> } <nl> } <nl> __kernel void arithm_flip_cols_C1_D1 ( __global char * src , int src_step , int src_offset , <nl> mmm a / modules / ocl / src / opencl / filter_sep_row . cl <nl> ppp b / modules / ocl / src / opencl / filter_sep_row . cl <nl> The info above maybe obsolete . <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_C1_D0 <nl> - ( __global const uchar * restrict src , <nl> - __global float * dst , <nl> - const int dst_cols , <nl> - const int dst_rows , <nl> - const int src_whole_cols , <nl> - const int src_whole_rows , <nl> - const int src_step_in_pixel , <nl> - const int src_offset_x , <nl> - const int src_offset_y , <nl> - const int dst_step_in_pixel , <nl> - const int radiusy , <nl> - __constant float * mat_kernel __attribute__ ( ( max_constant_size ( 4 * ( 2 * RADIUSX + 1 ) ) ) ) ) <nl> + ( __global const uchar * restrict src , <nl> + __global float * dst , <nl> + const int dst_cols , <nl> + const int dst_rows , <nl> + const int src_whole_cols , <nl> + const int src_whole_rows , <nl> + const int src_step_in_pixel , <nl> + const int src_offset_x , <nl> + const int src_offset_y , <nl> + const int dst_step_in_pixel , <nl> + const int radiusy , <nl> + __constant float * mat_kernel __attribute__ ( ( max_constant_size ( 4 * ( 2 * RADIUSX + 1 ) ) ) ) ) <nl> { <nl> int x = get_global_id ( 0 ) < < 2 ; <nl> int y = get_global_id ( 1 ) ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> uchar4 temp [ READ_TIMES_ROW ] ; <nl> <nl> __local uchar4 LDS_DAT [ LSIZE1 ] [ READ_TIMES_ROW * LSIZE0 + 1 ] ; <nl> - # ifdef BORDER_CONSTANT <nl> + # ifdef BORDER_CONSTANT <nl> int end_addr = mad24 ( src_whole_rows - 1 , src_step_in_pixel , src_whole_cols ) ; <nl> / / read pixels from src <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> int current_addr = start_addr + i * LSIZE0 * 4 ; <nl> current_addr = ( ( current_addr < end_addr ) & & ( current_addr > 0 ) ) ? current_addr : 0 ; <nl> temp [ i ] = * ( __global uchar4 * ) & src [ current_addr ] ; <nl> } <nl> / / judge if read out of boundary <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> temp [ i ] . x = ELEM ( start_x + i * LSIZE0 * 4 , 0 , src_whole_cols , 0 , temp [ i ] . x ) ; <nl> temp [ i ] . y = ELEM ( start_x + i * LSIZE0 * 4 + 1 , 0 , src_whole_cols , 0 , temp [ i ] . y ) ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> temp [ i ] . w = ELEM ( start_x + i * LSIZE0 * 4 + 3 , 0 , src_whole_cols , 0 , temp [ i ] . w ) ; <nl> temp [ i ] = ELEM ( start_y , 0 , src_whole_rows , ( uchar4 ) 0 , temp [ i ] ) ; <nl> } <nl> - # else <nl> + # else <nl> int not_all_in_range = ( start_x < 0 ) | ( start_x + READ_TIMES_ROW * LSIZE0 * 4 + 4 > src_whole_cols ) | ( start_y < 0 ) | ( start_y > = src_whole_rows ) ; <nl> int4 index [ READ_TIMES_ROW ] ; <nl> int4 addr ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> if ( not_all_in_range ) <nl> { <nl> / / judge if read out of boundary <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> index [ i ] . x = ADDR_L ( start_x + i * LSIZE0 * 4 , 0 , src_whole_cols , start_x + i * LSIZE0 * 4 ) ; <nl> index [ i ] . x = ADDR_R ( start_x + i * LSIZE0 * 4 , src_whole_cols , index [ i ] . x ) ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> s_y = ADDR_L ( start_y , 0 , src_whole_rows , start_y ) ; <nl> s_y = ADDR_R ( start_y , src_whole_rows , s_y ) ; <nl> / / read pixels from src <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> addr = mad24 ( ( int4 ) s_y , ( int4 ) src_step_in_pixel , index [ i ] ) ; <nl> temp [ i ] . x = src [ addr . x ] ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> else <nl> { <nl> / / read pixels from src <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> temp [ i ] = * ( __global uchar4 * ) & src [ start_addr + i * LSIZE0 * 4 ] ; <nl> } <nl> } <nl> - # endif <nl> + # endif <nl> <nl> / / save pixels to lds <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> LDS_DAT [ l_y ] [ l_x + i * LSIZE0 ] = temp [ i ] ; <nl> } <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> <nl> / / read pixels from lds and calculate the result <nl> sum = convert_float4 ( vload4 ( 0 , ( __local uchar * ) & LDS_DAT [ l_y ] [ l_x ] + RADIUSX + offset ) ) * mat_kernel [ RADIUSX ] ; <nl> - for ( i = 1 ; i < = RADIUSX ; i + + ) <nl> + for ( i = 1 ; i < = RADIUSX ; i + + ) <nl> { <nl> temp [ 0 ] = vload4 ( 0 , ( __local uchar * ) & LDS_DAT [ l_y ] [ l_x ] + RADIUSX + offset - i ) ; <nl> temp [ 1 ] = vload4 ( 0 , ( __local uchar * ) & LDS_DAT [ l_y ] [ l_x ] + RADIUSX + offset + i ) ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> } <nl> } <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_C4_D0 <nl> - ( __global const uchar4 * restrict src , <nl> - __global float4 * dst , <nl> - const int dst_cols , <nl> - const int dst_rows , <nl> - const int src_whole_cols , <nl> - const int src_whole_rows , <nl> - const int src_step_in_pixel , <nl> - const int src_offset_x , <nl> - const int src_offset_y , <nl> - const int dst_step_in_pixel , <nl> - const int radiusy , <nl> - __constant float * mat_kernel __attribute__ ( ( max_constant_size ( 4 * ( 2 * RADIUSX + 1 ) ) ) ) ) <nl> + ( __global const uchar4 * restrict src , <nl> + __global float4 * dst , <nl> + const int dst_cols , <nl> + const int dst_rows , <nl> + const int src_whole_cols , <nl> + const int src_whole_rows , <nl> + const int src_step_in_pixel , <nl> + const int src_offset_x , <nl> + const int src_offset_y , <nl> + const int dst_step_in_pixel , <nl> + const int radiusy , <nl> + __constant float * mat_kernel __attribute__ ( ( max_constant_size ( 4 * ( 2 * RADIUSX + 1 ) ) ) ) ) <nl> { <nl> int x = get_global_id ( 0 ) ; <nl> int y = get_global_id ( 1 ) ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> uchar4 temp [ READ_TIMES_ROW ] ; <nl> <nl> __local uchar4 LDS_DAT [ LSIZE1 ] [ READ_TIMES_ROW * LSIZE0 + 1 ] ; <nl> - # ifdef BORDER_CONSTANT <nl> + # ifdef BORDER_CONSTANT <nl> int end_addr = mad24 ( src_whole_rows - 1 , src_step_in_pixel , src_whole_cols ) ; <nl> / / read pixels from src <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> int current_addr = start_addr + i * LSIZE0 ; <nl> current_addr = ( ( current_addr < end_addr ) & & ( current_addr > 0 ) ) ? current_addr : 0 ; <nl> temp [ i ] = src [ current_addr ] ; <nl> } <nl> / / judge if read out of boundary <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> temp [ i ] = ELEM ( start_x + i * LSIZE0 , 0 , src_whole_cols , ( uchar4 ) 0 , temp [ i ] ) ; <nl> temp [ i ] = ELEM ( start_y , 0 , src_whole_rows , ( uchar4 ) 0 , temp [ i ] ) ; <nl> } <nl> - # else <nl> + # else <nl> int index [ READ_TIMES_ROW ] ; <nl> int s_x , s_y ; <nl> / / judge if read out of boundary <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> s_x = ADDR_L ( start_x + i * LSIZE0 , 0 , src_whole_cols , start_x + i * LSIZE0 ) ; <nl> s_x = ADDR_R ( start_x + i * LSIZE0 , src_whole_cols , s_x ) ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> index [ i ] = mad24 ( s_y , src_step_in_pixel , s_x ) ; <nl> } <nl> / / read pixels from src <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> temp [ i ] = src [ index [ i ] ] ; <nl> } <nl> - # endif <nl> + # endif <nl> <nl> / / save pixels to lds <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> LDS_DAT [ l_y ] [ l_x + i * LSIZE0 ] = temp [ i ] ; <nl> } <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> <nl> / / read pixels from lds and calculate the result <nl> sum = convert_float4 ( LDS_DAT [ l_y ] [ l_x + RADIUSX ] ) * mat_kernel [ RADIUSX ] ; <nl> - for ( i = 1 ; i < = RADIUSX ; i + + ) <nl> + for ( i = 1 ; i < = RADIUSX ; i + + ) <nl> { <nl> temp [ 0 ] = LDS_DAT [ l_y ] [ l_x + RADIUSX - i ] ; <nl> temp [ 1 ] = LDS_DAT [ l_y ] [ l_x + RADIUSX + i ] ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> } <nl> <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_C1_D5 <nl> - ( __global const float * restrict src , <nl> - __global float * dst , <nl> - const int dst_cols , <nl> - const int dst_rows , <nl> - const int src_whole_cols , <nl> - const int src_whole_rows , <nl> - const int src_step_in_pixel , <nl> - const int src_offset_x , <nl> - const int src_offset_y , <nl> - const int dst_step_in_pixel , <nl> - const int radiusy , <nl> - __constant float * mat_kernel __attribute__ ( ( max_constant_size ( 4 * ( 2 * RADIUSX + 1 ) ) ) ) ) <nl> + ( __global const float * restrict src , <nl> + __global float * dst , <nl> + const int dst_cols , <nl> + const int dst_rows , <nl> + const int src_whole_cols , <nl> + const int src_whole_rows , <nl> + const int src_step_in_pixel , <nl> + const int src_offset_x , <nl> + const int src_offset_y , <nl> + const int dst_step_in_pixel , <nl> + const int radiusy , <nl> + __constant float * mat_kernel __attribute__ ( ( max_constant_size ( 4 * ( 2 * RADIUSX + 1 ) ) ) ) ) <nl> { <nl> int x = get_global_id ( 0 ) ; <nl> int y = get_global_id ( 1 ) ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> float temp [ READ_TIMES_ROW ] ; <nl> <nl> __local float LDS_DAT [ LSIZE1 ] [ READ_TIMES_ROW * LSIZE0 + 1 ] ; <nl> - # ifdef BORDER_CONSTANT <nl> + # ifdef BORDER_CONSTANT <nl> int end_addr = mad24 ( src_whole_rows - 1 , src_step_in_pixel , src_whole_cols ) ; <nl> / / read pixels from src <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> int current_addr = start_addr + i * LSIZE0 ; <nl> current_addr = ( ( current_addr < end_addr ) & & ( current_addr > 0 ) ) ? current_addr : 0 ; <nl> temp [ i ] = src [ current_addr ] ; <nl> } <nl> / / judge if read out of boundary <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> - temp [ i ] = ELEM ( start_x + i * LSIZE0 , 0 , src_whole_cols , 0 , temp [ i ] ) ; <nl> - temp [ i ] = ELEM ( start_y , 0 , src_whole_rows , 0 , temp [ i ] ) ; <nl> + temp [ i ] = ELEM ( start_x + i * LSIZE0 , 0 , src_whole_cols , ( float ) 0 , temp [ i ] ) ; <nl> + temp [ i ] = ELEM ( start_y , 0 , src_whole_rows , ( float ) 0 , temp [ i ] ) ; <nl> } <nl> - # else <nl> + # else <nl> int index [ READ_TIMES_ROW ] ; <nl> int s_x , s_y ; <nl> / / judge if read out of boundary <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> s_x = ADDR_L ( start_x + i * LSIZE0 , 0 , src_whole_cols , start_x + i * LSIZE0 ) ; <nl> s_x = ADDR_R ( start_x + i * LSIZE0 , src_whole_cols , s_x ) ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> index [ i ] = mad24 ( s_y , src_step_in_pixel , s_x ) ; <nl> } <nl> / / read pixels from src <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> temp [ i ] = src [ index [ i ] ] ; <nl> } <nl> - # endif <nl> + # endif <nl> <nl> / / save pixels to lds <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> LDS_DAT [ l_y ] [ l_x + i * LSIZE0 ] = temp [ i ] ; <nl> } <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> <nl> / / read pixels from lds and calculate the result <nl> sum = LDS_DAT [ l_y ] [ l_x + RADIUSX ] * mat_kernel [ RADIUSX ] ; <nl> - for ( i = 1 ; i < = RADIUSX ; i + + ) <nl> + for ( i = 1 ; i < = RADIUSX ; i + + ) <nl> { <nl> temp [ 0 ] = LDS_DAT [ l_y ] [ l_x + RADIUSX - i ] ; <nl> temp [ 1 ] = LDS_DAT [ l_y ] [ l_x + RADIUSX + i ] ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> } <nl> <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_C4_D5 <nl> - ( __global const float4 * restrict src , <nl> - __global float4 * dst , <nl> - const int dst_cols , <nl> - const int dst_rows , <nl> - const int src_whole_cols , <nl> - const int src_whole_rows , <nl> - const int src_step_in_pixel , <nl> - const int src_offset_x , <nl> - const int src_offset_y , <nl> - const int dst_step_in_pixel , <nl> - const int radiusy , <nl> - __constant float * mat_kernel __attribute__ ( ( max_constant_size ( 4 * ( 2 * RADIUSX + 1 ) ) ) ) ) <nl> + ( __global const float4 * restrict src , <nl> + __global float4 * dst , <nl> + const int dst_cols , <nl> + const int dst_rows , <nl> + const int src_whole_cols , <nl> + const int src_whole_rows , <nl> + const int src_step_in_pixel , <nl> + const int src_offset_x , <nl> + const int src_offset_y , <nl> + const int dst_step_in_pixel , <nl> + const int radiusy , <nl> + __constant float * mat_kernel __attribute__ ( ( max_constant_size ( 4 * ( 2 * RADIUSX + 1 ) ) ) ) ) <nl> { <nl> int x = get_global_id ( 0 ) ; <nl> int y = get_global_id ( 1 ) ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> float4 temp [ READ_TIMES_ROW ] ; <nl> <nl> __local float4 LDS_DAT [ LSIZE1 ] [ READ_TIMES_ROW * LSIZE0 + 1 ] ; <nl> - # ifdef BORDER_CONSTANT <nl> + # ifdef BORDER_CONSTANT <nl> int end_addr = mad24 ( src_whole_rows - 1 , src_step_in_pixel , src_whole_cols ) ; <nl> / / read pixels from src <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> int current_addr = start_addr + i * LSIZE0 ; <nl> current_addr = ( ( current_addr < end_addr ) & & ( current_addr > 0 ) ) ? current_addr : 0 ; <nl> temp [ i ] = src [ current_addr ] ; <nl> } <nl> / / judge if read out of boundary <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> - temp [ i ] = ELEM ( start_x + i * LSIZE0 , 0 , src_whole_cols , 0 , temp [ i ] ) ; <nl> - temp [ i ] = ELEM ( start_y , 0 , src_whole_rows , 0 , temp [ i ] ) ; <nl> + temp [ i ] = ELEM ( start_x + i * LSIZE0 , 0 , src_whole_cols , ( float4 ) 0 , temp [ i ] ) ; <nl> + temp [ i ] = ELEM ( start_y , 0 , src_whole_rows , ( float4 ) 0 , temp [ i ] ) ; <nl> } <nl> - # else <nl> + # else <nl> int index [ READ_TIMES_ROW ] ; <nl> int s_x , s_y ; <nl> / / judge if read out of boundary <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> s_x = ADDR_L ( start_x + i * LSIZE0 , 0 , src_whole_cols , start_x + i * LSIZE0 ) ; <nl> s_x = ADDR_R ( start_x + i * LSIZE0 , src_whole_cols , s_x ) ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> index [ i ] = mad24 ( s_y , src_step_in_pixel , s_x ) ; <nl> } <nl> / / read pixels from src <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> temp [ i ] = src [ index [ i ] ] ; <nl> } <nl> - # endif <nl> + # endif <nl> <nl> / / save pixels to lds <nl> - for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> + for ( i = 0 ; i < READ_TIMES_ROW ; i + + ) <nl> { <nl> LDS_DAT [ l_y ] [ l_x + i * LSIZE0 ] = temp [ i ] ; <nl> } <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> <nl> / / read pixels from lds and calculate the result <nl> sum = LDS_DAT [ l_y ] [ l_x + RADIUSX ] * mat_kernel [ RADIUSX ] ; <nl> - for ( i = 1 ; i < = RADIUSX ; i + + ) <nl> + for ( i = 1 ; i < = RADIUSX ; i + + ) <nl> { <nl> temp [ 0 ] = LDS_DAT [ l_y ] [ l_x + RADIUSX - i ] ; <nl> temp [ 1 ] = LDS_DAT [ l_y ] [ l_x + RADIUSX + i ] ; <nl> __kernel __attribute__ ( ( reqd_work_group_size ( LSIZE0 , LSIZE1 , 1 ) ) ) void row_filter_ <nl> start_addr = mad24 ( y , dst_step_in_pixel , x ) ; <nl> dst [ start_addr ] = sum ; <nl> } <nl> + <nl> } <nl> + <nl> + <nl> mmm a / modules / ocl / src / opencl / filtering_laplacian . cl <nl> ppp b / modules / ocl / src / opencl / filtering_laplacian . cl <nl> __kernel void filter2D_C1_D0 ( __global uchar * src , int src_step , int src_offset_x <nl> int groupX_size = get_local_size ( 0 ) ; <nl> int groupX_id = get_group_id ( 0 ) ; <nl> <nl> - # define dst_align ( dst_offset_x & 3 ) <nl> + # define dst_align ( dst_offset_x & 3 ) <nl> int cols_start_index_group = src_offset_x - dst_align + groupX_size * groupX_id - ANX ; <nl> int rows_start_index = src_offset_y + ( gY < < ROWS_PER_GROUP_BITS ) - ANY ; <nl> <nl> __kernel void filter2D_C1_D0 ( __global uchar * src , int src_step , int src_offset_x <nl> { <nl> if ( ( rows_start_index - src_offset_y ) + i < rows + ANY ) <nl> { <nl> - # ifdef BORDER_CONSTANT <nl> + # ifdef BORDER_CONSTANT <nl> int selected_row = rows_start_index + i ; <nl> int selected_cols = cols_start_index_group + lX ; <nl> <nl> __kernel void filter2D_C1_D0 ( __global uchar * src , int src_step , int src_offset_x <nl> data = con ? data : 0 ; <nl> local_data [ i * LOCAL_MEM_STEP + lX + groupX_size ] = data ; <nl> } <nl> - # else <nl> + # else <nl> int selected_row = ADDR_H ( rows_start_index + i , 0 , wholerows ) ; <nl> selected_row = ADDR_B ( rows_start_index + i , wholerows , selected_row ) ; <nl> <nl> __kernel void filter2D_C1_D0 ( __global uchar * src , int src_step , int src_offset_x <nl> data = * ( src + selected_row * src_step + selected_cols ) ; <nl> local_data [ i * LOCAL_MEM_STEP + lX + groupX_size ] = data ; <nl> } <nl> - # endif <nl> + # endif <nl> } <nl> } <nl> } <nl> __kernel void filter2D_C1_D0 ( __global uchar * src , int src_step , int src_offset_x <nl> <nl> for ( int i = 0 ; i < ANCHOR ; i + + ) <nl> { <nl> - # pragma unroll 3 <nl> - for ( int j = 0 ; j < ANCHOR ; j + + ) <nl> - { <nl> + # pragma unroll 3 <nl> + for ( int j = 0 ; j < ANCHOR ; j + + ) <nl> + { <nl> if ( dst_rows_index < dst_rows_end ) <nl> { <nl> - int local_row = ( lX > > THREADS_PER_ROW_BIT ) + i ; <nl> - int local_cols = ( ( lX % THREADS_PER_ROW ) < < ELEMENTS_PER_THREAD_BIT ) + j ; <nl> + int local_row = ( lX > > THREADS_PER_ROW_BIT ) + i ; <nl> + int local_cols = ( ( lX % THREADS_PER_ROW ) < < ELEMENTS_PER_THREAD_BIT ) + j ; <nl> <nl> - data = vload4 ( 0 , local_data + local_row * LOCAL_MEM_STEP + local_cols ) ; <nl> - sum = sum + ( mat_kernel [ i * ANCHOR + j ] * convert_int4_sat ( data ) ) ; <nl> - } <nl> + data = vload4 ( 0 , local_data + local_row * LOCAL_MEM_STEP + local_cols ) ; <nl> + sum = sum + ( mat_kernel [ i * ANCHOR + j ] * convert_int4_sat ( data ) ) ; <nl> + } <nl> } <nl> } <nl> <nl> __kernel void filter2D_C1_D0 ( __global uchar * src , int src_step , int src_offset_x <nl> sum . w = ( ( dst_cols_index + 3 > = dst_cols_start ) & & ( dst_cols_index + 3 < dst_cols_end ) ) ? sum . w : dst_data . w ; <nl> * ( ( __global uchar4 * ) ( dst + dst_rows_index * dst_step + dst_cols_index ) ) = convert_uchar4_sat ( sum ) ; <nl> } <nl> - } <nl> + } <nl> } <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / 32FC1 / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> __kernel void filter2D_C1_D5 ( __global float * src , int src_step , int src_offset_x <nl> int groupX_size = get_local_size ( 0 ) ; <nl> int groupX_id = get_group_id ( 0 ) ; <nl> <nl> - # define dst_align ( dst_offset_x & 3 ) <nl> + # define dst_align ( dst_offset_x & 3 ) <nl> int cols_start_index_group = src_offset_x - dst_align + groupX_size * groupX_id - ANX ; <nl> int rows_start_index = src_offset_y + ( gY < < ROWS_PER_GROUP_BITS ) - ANY ; <nl> <nl> __kernel void filter2D_C1_D5 ( __global float * src , int src_step , int src_offset_x <nl> { <nl> if ( ( rows_start_index - src_offset_y ) + i < rows + ANY ) <nl> { <nl> - # ifdef BORDER_CONSTANT <nl> + # ifdef BORDER_CONSTANT <nl> int selected_row = rows_start_index + i ; <nl> int selected_cols = cols_start_index_group + lX ; <nl> <nl> __kernel void filter2D_C1_D5 ( __global float * src , int src_step , int src_offset_x <nl> data = con ? data : 0 ; <nl> local_data [ i * LOCAL_MEM_STEP + lX + groupX_size ] = data ; <nl> } <nl> - # else <nl> + # else <nl> int selected_row = ADDR_H ( rows_start_index + i , 0 , wholerows ) ; <nl> selected_row = ADDR_B ( rows_start_index + i , wholerows , selected_row ) ; <nl> <nl> __kernel void filter2D_C1_D5 ( __global float * src , int src_step , int src_offset_x <nl> data = * ( ( __global float * ) ( ( __global char * ) src + selected_row * src_step + ( selected_cols < < 2 ) ) ) ; <nl> local_data [ i * LOCAL_MEM_STEP + lX + groupX_size ] = data ; <nl> } <nl> - # endif <nl> + # endif <nl> } <nl> } <nl> } <nl> __kernel void filter2D_C1_D5 ( __global float * src , int src_step , int src_offset_x <nl> <nl> for ( int i = 0 ; i < ANCHOR ; i + + ) <nl> { <nl> - # pragma unroll 3 <nl> - for ( int j = 0 ; j < ANCHOR ; j + + ) <nl> - { <nl> + # pragma unroll 3 <nl> + for ( int j = 0 ; j < ANCHOR ; j + + ) <nl> + { <nl> if ( dst_rows_index < dst_rows_end ) <nl> { <nl> - int local_row = ( lX > > THREADS_PER_ROW_BIT ) + i ; <nl> - int local_cols = ( ( lX % THREADS_PER_ROW ) < < ELEMENTS_PER_THREAD_BIT ) + j ; <nl> + int local_row = ( lX > > THREADS_PER_ROW_BIT ) + i ; <nl> + int local_cols = ( ( lX % THREADS_PER_ROW ) < < ELEMENTS_PER_THREAD_BIT ) + j ; <nl> <nl> - data = vload4 ( 0 , local_data + local_row * LOCAL_MEM_STEP + local_cols ) ; <nl> - sum = sum + ( mat_kernel [ i * ANCHOR + j ] * data ) ; <nl> - } <nl> + data = vload4 ( 0 , local_data + local_row * LOCAL_MEM_STEP + local_cols ) ; <nl> + sum = sum + ( ( float ) ( mat_kernel [ i * ANCHOR + j ] ) * data ) ; <nl> + } <nl> } <nl> } <nl> <nl> __kernel void filter2D_C1_D5 ( __global float * src , int src_step , int src_offset_x <nl> <nl> * ( ( __global float4 * ) ( ( __global char * ) dst + dst_rows_index * dst_step + ( dst_cols_index < < 2 ) ) ) = sum ; <nl> } <nl> - } <nl> + } <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> __kernel void filter2D_C4_D0 ( __global uchar4 * src , int src_step , int src_offset_ <nl> int groupX_size = get_local_size ( 0 ) ; <nl> int groupX_id = get_group_id ( 0 ) ; <nl> <nl> - # define dst_align ( dst_offset_x & 3 ) <nl> + # define dst_align ( dst_offset_x & 3 ) <nl> int cols_start_index_group = src_offset_x - dst_align + groupX_size * groupX_id - ANX ; <nl> int rows_start_index = src_offset_y + ( gY < < ROWS_PER_GROUP_BITS ) - ANY ; <nl> <nl> __kernel void filter2D_C4_D0 ( __global uchar4 * src , int src_step , int src_offset_ <nl> { <nl> if ( ( rows_start_index - src_offset_y ) + i < rows + ANY ) <nl> { <nl> - # ifdef BORDER_CONSTANT <nl> + # ifdef BORDER_CONSTANT <nl> int selected_row = rows_start_index + i ; <nl> int selected_cols = cols_start_index_group + lX ; <nl> <nl> __kernel void filter2D_C4_D0 ( __global uchar4 * src , int src_step , int src_offset_ <nl> data = con ? data : 0 ; <nl> local_data [ i * LOCAL_MEM_STEP + lX + groupX_size ] = data ; <nl> } <nl> - # else <nl> + # else <nl> int selected_row = ADDR_H ( rows_start_index + i , 0 , wholerows ) ; <nl> selected_row = ADDR_B ( rows_start_index + i , wholerows , selected_row ) ; <nl> <nl> __kernel void filter2D_C4_D0 ( __global uchar4 * src , int src_step , int src_offset_ <nl> data = * ( ( __global uchar4 * ) ( ( __global char * ) src + selected_row * src_step + ( selected_cols < < 2 ) ) ) ; <nl> local_data [ i * LOCAL_MEM_STEP + lX + groupX_size ] = data ; <nl> } <nl> - # endif <nl> + # endif <nl> } <nl> } <nl> } <nl> __kernel void filter2D_C4_D0 ( __global uchar4 * src , int src_step , int src_offset_ <nl> <nl> for ( int i = 0 ; i < ANCHOR ; i + + ) <nl> { <nl> - # pragma unroll 3 <nl> - for ( int j = 0 ; j < ANCHOR ; j + + ) <nl> - { <nl> + # pragma unroll 3 <nl> + for ( int j = 0 ; j < ANCHOR ; j + + ) <nl> + { <nl> if ( dst_rows_index < dst_rows_end ) <nl> { <nl> - int local_row = ( lX > > THREADS_PER_ROW_BIT ) + i ; <nl> - int local_cols = ( ( lX % THREADS_PER_ROW ) < < ELEMENTS_PER_THREAD_BIT ) + j ; <nl> + int local_row = ( lX > > THREADS_PER_ROW_BIT ) + i ; <nl> + int local_cols = ( ( lX % THREADS_PER_ROW ) < < ELEMENTS_PER_THREAD_BIT ) + j ; <nl> <nl> - data = vload16 ( 0 , ( __local uchar * ) ( local_data + local_row * LOCAL_MEM_STEP + local_cols ) ) ; <nl> - sum = sum + ( mat_kernel [ i * ANCHOR + j ] * convert_int16_sat ( data ) ) ; <nl> - } <nl> + data = vload16 ( 0 , ( __local uchar * ) ( local_data + local_row * LOCAL_MEM_STEP + local_cols ) ) ; <nl> + sum = sum + ( mat_kernel [ i * ANCHOR + j ] * convert_int16_sat ( data ) ) ; <nl> + } <nl> } <nl> } <nl> <nl> __kernel void filter2D_C4_D5 ( __global float4 * src , int src_step , int src_offset_ <nl> { <nl> if ( ( rows_start_index - src_offset_y ) + i < rows + ANY ) <nl> { <nl> - # ifdef BORDER_CONSTANT <nl> + # ifdef BORDER_CONSTANT <nl> int selected_row = rows_start_index + i ; <nl> int selected_cols = cols_start_index_group + lX ; <nl> <nl> __kernel void filter2D_C4_D5 ( __global float4 * src , int src_step , int src_offset_ <nl> data = con ? data : 0 ; <nl> local_data [ i * LOCAL_MEM_STEP + lX + groupX_size ] = data ; <nl> } <nl> - # else <nl> + # else <nl> int selected_row = ADDR_H ( rows_start_index + i , 0 , wholerows ) ; <nl> selected_row = ADDR_B ( rows_start_index + i , wholerows , selected_row ) ; <nl> <nl> __kernel void filter2D_C4_D5 ( __global float4 * src , int src_step , int src_offset_ <nl> data = * ( ( __global float4 * ) ( ( __global char * ) src + selected_row * src_step + ( selected_cols < < 4 ) ) ) ; <nl> local_data [ i * LOCAL_MEM_STEP_C4 + lX + groupX_size ] = data ; <nl> } <nl> - # endif <nl> + # endif <nl> } <nl> } <nl> } <nl> __kernel void filter2D_C4_D5 ( __global float4 * src , int src_step , int src_offset_ <nl> <nl> for ( int i = 0 ; i < ANCHOR ; i + + ) <nl> { <nl> - for ( int j = 0 ; j < ANCHOR ; j + + ) <nl> - { <nl> - int local_cols = lX + j ; <nl> - sum = sum + mat_kernel [ i * ANCHOR + j ] * local_data [ i * LOCAL_MEM_STEP_C4 + local_cols ] ; <nl> + for ( int j = 0 ; j < ANCHOR ; j + + ) <nl> + { <nl> + int local_cols = lX + j ; <nl> + sum = sum + ( ( float ) mat_kernel [ i * ANCHOR + j ] * local_data [ i * LOCAL_MEM_STEP_C4 + local_cols ] ) ; <nl> } <nl> } <nl> <nl> mmm a / modules / ocl / src / opencl / imgproc_integral . cl <nl> ppp b / modules / ocl / src / opencl / imgproc_integral . cl <nl> <nl> / / M * / <nl> <nl> # if defined ( DOUBLE_SUPPORT ) <nl> + # ifdef cl_khr_fp64 <nl> # pragma OPENCL EXTENSION cl_khr_fp64 : enable <nl> + # elif defined ( cl_amd_fp64 ) <nl> + # pragma OPENCL EXTENSION cl_amd_fp64 : enable <nl> + # endif <nl> # endif <nl> # define LSIZE 256 <nl> # define LSIZE_1 255 <nl> kernel void integral_cols ( __global uchar4 * src , __global int * sum , __global float <nl> gid = gid < < 1 ; <nl> for ( int i = 0 ; i < rows ; i = i + LSIZE_1 ) <nl> { <nl> - src_t [ 0 ] = ( i + lid < rows ? convert_int4 ( src [ src_offset + ( lid + i ) * src_step + gid ] ) : 0 ) ; <nl> - src_t [ 1 ] = ( i + lid < rows ? convert_int4 ( src [ src_offset + ( lid + i ) * src_step + gid + 1 ] ) : 0 ) ; <nl> + src_t [ 0 ] = ( i + lid < rows ? convert_int4 ( src [ src_offset + ( lid + i ) * src_step + min ( gid , ( uint ) cols - 1 ) ] ) : 0 ) ; <nl> + src_t [ 1 ] = ( i + lid < rows ? convert_int4 ( src [ src_offset + ( lid + i ) * src_step + min ( gid + 1 , ( uint ) cols - 1 ) ] ) : 0 ) ; <nl> <nl> sum_t [ 0 ] = ( i = = 0 ? 0 : lm_sum [ 0 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> - sqsum_t [ 0 ] = ( i = = 0 ? 0 : lm_sqsum [ 0 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> + sqsum_t [ 0 ] = ( i = = 0 ? ( float4 ) 0 : lm_sqsum [ 0 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> sum_t [ 1 ] = ( i = = 0 ? 0 : lm_sum [ 1 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> - sqsum_t [ 1 ] = ( i = = 0 ? 0 : lm_sqsum [ 1 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> + sqsum_t [ 1 ] = ( i = = 0 ? ( float4 ) 0 : lm_sqsum [ 1 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> barrier ( CLK_LOCAL_MEM_FENCE ) ; <nl> <nl> int bf_loc = lid + GET_CONFLICT_OFFSET ( lid ) ; <nl> kernel void integral_cols ( __global uchar4 * src , __global int * sum , __global float <nl> } <nl> barrier ( CLK_LOCAL_MEM_FENCE ) ; <nl> int loc_s0 = gid * dst_step + i + lid - 1 - pre_invalid * dst_step / 4 , loc_s1 = loc_s0 + dst_step ; <nl> - if ( lid > 0 & & ( i + lid ) < = rows ) { <nl> + if ( lid > 0 & & ( i + lid ) < = rows ) <nl> + { <nl> lm_sum [ 0 ] [ bf_loc ] + = sum_t [ 0 ] ; <nl> lm_sum [ 1 ] [ bf_loc ] + = sum_t [ 1 ] ; <nl> lm_sqsum [ 0 ] [ bf_loc ] + = sqsum_t [ 0 ] ; <nl> kernel void integral_rows ( __global int4 * srcsum , __global float4 * srcsqsum , __glo <nl> src_step = src_step > > 4 ; <nl> for ( int i = 0 ; i < rows ; i = i + LSIZE_1 ) <nl> { <nl> - src_t [ 0 ] = i + lid < rows ? srcsum [ ( lid + i ) * src_step + gid * 2 ] : 0 ; <nl> - sqsrc_t [ 0 ] = i + lid < rows ? srcsqsum [ ( lid + i ) * src_step + gid * 2 ] : 0 ; <nl> - src_t [ 1 ] = i + lid < rows ? srcsum [ ( lid + i ) * src_step + gid * 2 + 1 ] : 0 ; <nl> - sqsrc_t [ 1 ] = i + lid < rows ? srcsqsum [ ( lid + i ) * src_step + gid * 2 + 1 ] : 0 ; <nl> + src_t [ 0 ] = i + lid < rows ? srcsum [ ( lid + i ) * src_step + gid * 2 ] : ( int4 ) 0 ; <nl> + sqsrc_t [ 0 ] = i + lid < rows ? srcsqsum [ ( lid + i ) * src_step + gid * 2 ] : ( float4 ) 0 ; <nl> + src_t [ 1 ] = i + lid < rows ? srcsum [ ( lid + i ) * src_step + gid * 2 + 1 ] : ( int4 ) 0 ; <nl> + sqsrc_t [ 1 ] = i + lid < rows ? srcsqsum [ ( lid + i ) * src_step + gid * 2 + 1 ] : ( float4 ) 0 ; <nl> <nl> sum_t [ 0 ] = ( i = = 0 ? 0 : lm_sum [ 0 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> - sqsum_t [ 0 ] = ( i = = 0 ? 0 : lm_sqsum [ 0 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> + sqsum_t [ 0 ] = ( i = = 0 ? ( float4 ) 0 : lm_sqsum [ 0 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> sum_t [ 1 ] = ( i = = 0 ? 0 : lm_sum [ 1 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> - sqsum_t [ 1 ] = ( i = = 0 ? 0 : lm_sqsum [ 1 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> + sqsum_t [ 1 ] = ( i = = 0 ? ( float4 ) 0 : lm_sqsum [ 1 ] [ LSIZE_2 + LOG_LSIZE ] ) ; <nl> barrier ( CLK_LOCAL_MEM_FENCE ) ; <nl> <nl> int bf_loc = lid + GET_CONFLICT_OFFSET ( lid ) ; <nl> kernel void integral_rows ( __global int4 * srcsum , __global float4 * srcsqsum , __glo <nl> barrier ( CLK_LOCAL_MEM_FENCE ) ; <nl> if ( gid = = 0 & & ( i + lid ) < = rows ) <nl> { <nl> - sum [ sum_offset + i + lid ] = 0 ; <nl> - sqsum [ sqsum_offset + i + lid ] = 0 ; <nl> + sum [ sum_offset + i + lid ] = 0 ; <nl> + sqsum [ sqsum_offset + i + lid ] = 0 ; <nl> } <nl> if ( i + lid = = 0 ) <nl> { <nl> int loc0 = gid * 2 * sum_step ; <nl> int loc1 = gid * 2 * sqsum_step ; <nl> - for ( int k = 1 ; k < = 8 ; k + + ) <nl> + for ( int k = 1 ; k < = 8 ; k + + ) <nl> { <nl> if ( gid * 8 + k > cols ) break ; <nl> sum [ sum_offset + loc0 + k * sum_step / 4 ] = 0 ; <nl> kernel void integral_rows ( __global int4 * srcsum , __global float4 * srcsqsum , __glo <nl> } <nl> int loc_s0 = sum_offset + gid * 2 * sum_step + sum_step / 4 + i + lid , loc_s1 = loc_s0 + sum_step ; <nl> int loc_sq0 = sqsum_offset + gid * 2 * sqsum_step + sqsum_step / 4 + i + lid , loc_sq1 = loc_sq0 + sqsum_step ; <nl> - if ( lid > 0 & & ( i + lid ) < = rows ) { <nl> + if ( lid > 0 & & ( i + lid ) < = rows ) <nl> + { <nl> lm_sum [ 0 ] [ bf_loc ] + = sum_t [ 0 ] ; <nl> lm_sum [ 1 ] [ bf_loc ] + = sum_t [ 1 ] ; <nl> lm_sqsum [ 0 ] [ bf_loc ] + = sqsum_t [ 0 ] ; <nl> mmm a / modules / ocl / src / opencl / imgproc_warpAffine . cl <nl> ppp b / modules / ocl / src / opencl / imgproc_warpAffine . cl <nl> <nl> / / warpAffine kernel <nl> / / support data types : CV_8UC1 , CV_8UC4 , CV_32FC1 , CV_32FC4 , and three interpolation methods : NN , Linear , Cubic . <nl> <nl> - # if defined DOUBLE_SUPPORT <nl> + # if defined ( DOUBLE_SUPPORT ) <nl> + # ifdef cl_khr_fp64 <nl> # pragma OPENCL EXTENSION cl_khr_fp64 : enable <nl> + # elif defined ( cl_amd_fp64 ) <nl> + # pragma OPENCL EXTENSION cl_amd_fp64 : enable <nl> + # endif <nl> typedef double F ; <nl> typedef double4 F4 ; <nl> # define convert_F4 convert_double4 <nl> typedef float4 F4 ; <nl> # define convert_F4 convert_float4 <nl> # endif <nl> <nl> - <nl> # define INTER_BITS 5 <nl> # define INTER_TAB_SIZE ( 1 < < INTER_BITS ) <nl> # define INTER_SCALE 1 . f / INTER_TAB_SIZE <nl> inline void interpolateCubic ( float x , float * coeffs ) <nl> / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 8UC1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> __kernel void warpAffineNN_C1_D0 ( __global uchar const * restrict src , __global uchar * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineNN_C1_D0 ( __global uchar const * restrict src , __global u <nl> sval . s1 = scon . s1 ? src [ spos . s1 ] : 0 ; <nl> sval . s2 = scon . s2 ? src [ spos . s2 ] : 0 ; <nl> sval . s3 = scon . s3 ? src [ spos . s3 ] : 0 ; <nl> - dval = convert_uchar4 ( dcon ! = 0 ) ? sval : dval ; <nl> + dval = convert_uchar4 ( dcon ) ! = ( uchar4 ) ( 0 , 0 , 0 , 0 ) ? sval : dval ; <nl> * d = dval ; <nl> } <nl> } <nl> <nl> __kernel void warpAffineLinear_C1_D0 ( __global const uchar * restrict src , __global uchar * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineLinear_C1_D0 ( __global const uchar * restrict src , __glob <nl> spos1 = src_offset + sy * srcStep + sx + 1 ; <nl> spos2 = src_offset + ( sy + 1 ) * srcStep + sx ; <nl> spos3 = src_offset + ( sy + 1 ) * srcStep + sx + 1 ; <nl> - <nl> + <nl> v0 . s0 = scon0 . s0 ? src [ spos0 . s0 ] : 0 ; <nl> v1 . s0 = scon1 . s0 ? src [ spos1 . s0 ] : 0 ; <nl> v2 . s0 = scon2 . s0 ? src [ spos2 . s0 ] : 0 ; <nl> __kernel void warpAffineLinear_C1_D0 ( __global const uchar * restrict src , __glob <nl> v1 . s3 = scon1 . s3 ? src [ spos1 . s3 ] : 0 ; <nl> v2 . s3 = scon2 . s3 ? src [ spos2 . s3 ] : 0 ; <nl> v3 . s3 = scon3 . s3 ? src [ spos3 . s3 ] : 0 ; <nl> - <nl> + <nl> short4 itab0 , itab1 , itab2 , itab3 ; <nl> float4 taby , tabx ; <nl> taby = INTER_SCALE * convert_float4 ( ay ) ; <nl> tabx = INTER_SCALE * convert_float4 ( ax ) ; <nl> <nl> - itab0 = convert_short4_sat ( ( ( 1 . 0f - taby ) * ( 1 . 0f - tabx ) * INTER_REMAP_COEF_SCALE ) ) ; <nl> - itab1 = convert_short4_sat ( ( ( 1 . 0f - taby ) * tabx * INTER_REMAP_COEF_SCALE ) ) ; <nl> - itab2 = convert_short4_sat ( ( taby * ( 1 . 0f - tabx ) * INTER_REMAP_COEF_SCALE ) ) ; <nl> - itab3 = convert_short4_sat ( ( taby * tabx * INTER_REMAP_COEF_SCALE ) ) ; <nl> + itab0 = convert_short4_sat ( ( ( 1 . 0f - taby ) * ( 1 . 0f - tabx ) * ( float4 ) INTER_REMAP_COEF_SCALE ) ) ; <nl> + itab1 = convert_short4_sat ( ( ( 1 . 0f - taby ) * tabx * ( float4 ) INTER_REMAP_COEF_SCALE ) ) ; <nl> + itab2 = convert_short4_sat ( ( taby * ( 1 . 0f - tabx ) * ( float4 ) INTER_REMAP_COEF_SCALE ) ) ; <nl> + itab3 = convert_short4_sat ( ( taby * tabx * ( float4 ) INTER_REMAP_COEF_SCALE ) ) ; <nl> <nl> <nl> int4 val ; <nl> uchar4 tval ; <nl> val = convert_int4 ( v0 ) * convert_int4 ( itab0 ) + convert_int4 ( v1 ) * convert_int4 ( itab1 ) <nl> - + convert_int4 ( v2 ) * convert_int4 ( itab2 ) + convert_int4 ( v3 ) * convert_int4 ( itab3 ) ; <nl> + + convert_int4 ( v2 ) * convert_int4 ( itab2 ) + convert_int4 ( v3 ) * convert_int4 ( itab3 ) ; <nl> tval = convert_uchar4_sat ( ( val + ( 1 < < ( INTER_REMAP_COEF_BITS - 1 ) ) ) > > INTER_REMAP_COEF_BITS ) ; <nl> <nl> __global uchar4 * d = ( __global uchar4 * ) ( dst + dst_offset + dy * dstStep + dx ) ; <nl> __kernel void warpAffineLinear_C1_D0 ( __global const uchar * restrict src , __glob <nl> } <nl> <nl> __kernel void warpAffineCubic_C1_D0 ( __global uchar * src , __global uchar * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineCubic_C1_D0 ( __global uchar * src , __global uchar * dst , <nl> <nl> # pragma unroll 4 <nl> for ( i = 0 ; i < 4 ; i + + ) <nl> - for ( j = 0 ; j < 4 ; j + + ) <nl> - { <nl> - v [ i * 4 + j ] = ( sx + j > = 0 & & sx + j < src_cols & & sy + i > = 0 & & sy + i < src_rows ) ? src [ src_offset + ( sy + i ) * srcStep + ( sx + j ) ] : 0 ; <nl> - } <nl> + for ( j = 0 ; j < 4 ; j + + ) <nl> + { <nl> + v [ i * 4 + j ] = ( sx + j > = 0 & & sx + j < src_cols & & sy + i > = 0 & & sy + i < src_rows ) ? src [ src_offset + ( sy + i ) * srcStep + ( sx + j ) ] : 0 ; <nl> + } <nl> <nl> short itab [ 16 ] ; <nl> float tab1y [ 4 ] , tab1x [ 4 ] ; <nl> __kernel void warpAffineCubic_C1_D0 ( __global uchar * src , __global uchar * dst , <nl> if ( itab [ ( k1 < < 2 ) + k2 ] < itab [ ( mk1 < < 2 ) + mk2 ] ) <nl> mk1 = k1 , mk2 = k2 ; <nl> else if ( itab [ ( k1 < < 2 ) + k2 ] > itab [ ( Mk1 < < 2 ) + Mk2 ] ) <nl> - Mk1 = k1 , Mk2 = k2 ; <nl> + Mk1 = k1 , Mk2 = k2 ; <nl> } <nl> diff < 0 ? ( itab [ ( Mk1 < < 2 ) + Mk2 ] = ( short ) ( itab [ ( Mk1 < < 2 ) + Mk2 ] - diff ) ) : ( itab [ ( mk1 < < 2 ) + mk2 ] = ( short ) ( itab [ ( mk1 < < 2 ) + mk2 ] - diff ) ) ; <nl> } <nl> __kernel void warpAffineCubic_C1_D0 ( __global uchar * src , __global uchar * dst , <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> __kernel void warpAffineNN_C4_D0 ( __global uchar4 const * restrict src , __global uchar4 * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineNN_C4_D0 ( __global uchar4 const * restrict src , __global <nl> } <nl> <nl> __kernel void warpAffineLinear_C4_D0 ( __global uchar4 const * restrict src , __global uchar4 * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineLinear_C4_D0 ( __global uchar4 const * restrict src , __glo <nl> } <nl> <nl> __kernel void warpAffineCubic_C4_D0 ( __global uchar4 const * restrict src , __global uchar4 * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineCubic_C4_D0 ( __global uchar4 const * restrict src , __glob <nl> int i , j ; <nl> # pragma unroll 4 <nl> for ( i = 0 ; i < 4 ; i + + ) <nl> - for ( j = 0 ; j < 4 ; j + + ) <nl> - { <nl> - v [ i * 4 + j ] = ( sx + j > = 0 & & sx + j < src_cols & & sy + i > = 0 & & sy + i < src_rows ) ? ( src [ src_offset + ( sy + i ) * srcStep + ( sx + j ) ] ) : ( uchar4 ) 0 ; <nl> - } <nl> + for ( j = 0 ; j < 4 ; j + + ) <nl> + { <nl> + v [ i * 4 + j ] = ( sx + j > = 0 & & sx + j < src_cols & & sy + i > = 0 & & sy + i < src_rows ) ? ( src [ src_offset + ( sy + i ) * srcStep + ( sx + j ) ] ) : ( uchar4 ) 0 ; <nl> + } <nl> int itab [ 16 ] ; <nl> float tab1y [ 4 ] , tab1x [ 4 ] ; <nl> float axx , ayy ; <nl> __kernel void warpAffineCubic_C4_D0 ( __global uchar4 const * restrict src , __glob <nl> int diff = isum - INTER_REMAP_COEF_SCALE ; <nl> int Mk1 = 2 , Mk2 = 2 , mk1 = 2 , mk2 = 2 ; <nl> <nl> - for ( k1 = 2 ; k1 < 4 ; k1 + + ) <nl> + for ( k1 = 2 ; k1 < 4 ; k1 + + ) <nl> for ( k2 = 2 ; k2 < 4 ; k2 + + ) <nl> { <nl> <nl> if ( itab [ ( k1 < < 2 ) + k2 ] < itab [ ( mk1 < < 2 ) + mk2 ] ) <nl> mk1 = k1 , mk2 = k2 ; <nl> else if ( itab [ ( k1 < < 2 ) + k2 ] > itab [ ( Mk1 < < 2 ) + Mk2 ] ) <nl> - Mk1 = k1 , Mk2 = k2 ; <nl> + Mk1 = k1 , Mk2 = k2 ; <nl> } <nl> <nl> diff < 0 ? ( itab [ ( Mk1 < < 2 ) + Mk2 ] = ( short ) ( itab [ ( Mk1 < < 2 ) + Mk2 ] - diff ) ) : ( itab [ ( mk1 < < 2 ) + mk2 ] = ( short ) ( itab [ ( mk1 < < 2 ) + mk2 ] - diff ) ) ; <nl> __kernel void warpAffineCubic_C4_D0 ( __global uchar4 const * restrict src , __glob <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> __kernel void warpAffineNN_C1_D5 ( __global float * src , __global float * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineNN_C1_D5 ( __global float * src , __global float * dst , int <nl> } <nl> <nl> __kernel void warpAffineLinear_C1_D5 ( __global float * src , __global float * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineLinear_C1_D5 ( __global float * src , __global float * dst , <nl> sum + = v0 * tab [ 0 ] + v1 * tab [ 1 ] + v2 * tab [ 2 ] + v3 * tab [ 3 ] ; <nl> if ( dx > = 0 & & dx < dst_cols & & dy > = 0 & & dy < dst_rows ) <nl> dst [ ( dst_offset > > 2 ) + dy * dstStep + dx ] = sum ; <nl> - } <nl> + } <nl> } <nl> <nl> __kernel void warpAffineCubic_C1_D5 ( __global float * src , __global float * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineCubic_C1_D5 ( __global float * src , __global float * dst , <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> __kernel void warpAffineNN_C4_D5 ( __global float4 * src , __global float4 * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineNN_C4_D5 ( __global float4 * src , __global float4 * dst , i <nl> short sy0 = ( short ) ( Y0 > > AB_BITS ) ; <nl> <nl> if ( dx > = 0 & & dx < dst_cols & & dy > = 0 & & dy < dst_rows ) <nl> - dst [ ( dst_offset > > 4 ) + dy * ( dstStep > > 2 ) + dx ] = ( sx0 > = 0 & & sx0 < src_cols & & sy0 > = 0 & & sy0 < src_rows ) ? src [ ( src_offset > > 4 ) + sy0 * ( srcStep > > 2 ) + sx0 ] : 0 ; <nl> + dst [ ( dst_offset > > 4 ) + dy * ( dstStep > > 2 ) + dx ] = ( sx0 > = 0 & & sx0 < src_cols & & sy0 > = 0 & & sy0 < src_rows ) ? src [ ( src_offset > > 4 ) + sy0 * ( srcStep > > 2 ) + sx0 ] : ( float4 ) 0 ; <nl> } <nl> } <nl> <nl> __kernel void warpAffineLinear_C4_D5 ( __global float4 * src , __global float4 * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineLinear_C4_D5 ( __global float4 * src , __global float4 * ds <nl> <nl> float4 v0 , v1 , v2 , v3 ; <nl> <nl> - v0 = ( sx0 > = 0 & & sx0 < src_cols & & sy0 > = 0 & & sy0 < src_rows ) ? src [ src_offset + sy0 * srcStep + sx0 ] : 0 ; <nl> - v1 = ( sx0 + 1 > = 0 & & sx0 + 1 < src_cols & & sy0 > = 0 & & sy0 < src_rows ) ? src [ src_offset + sy0 * srcStep + sx0 + 1 ] : 0 ; <nl> - v2 = ( sx0 > = 0 & & sx0 < src_cols & & sy0 + 1 > = 0 & & sy0 + 1 < src_rows ) ? src [ src_offset + ( sy0 + 1 ) * srcStep + sx0 ] : 0 ; <nl> - v3 = ( sx0 + 1 > = 0 & & sx0 + 1 < src_cols & & sy0 + 1 > = 0 & & sy0 + 1 < src_rows ) ? src [ src_offset + ( sy0 + 1 ) * srcStep + sx0 + 1 ] : 0 ; <nl> + v0 = ( sx0 > = 0 & & sx0 < src_cols & & sy0 > = 0 & & sy0 < src_rows ) ? src [ src_offset + sy0 * srcStep + sx0 ] : ( float4 ) 0 ; <nl> + v1 = ( sx0 + 1 > = 0 & & sx0 + 1 < src_cols & & sy0 > = 0 & & sy0 < src_rows ) ? src [ src_offset + sy0 * srcStep + sx0 + 1 ] : ( float4 ) 0 ; <nl> + v2 = ( sx0 > = 0 & & sx0 < src_cols & & sy0 + 1 > = 0 & & sy0 + 1 < src_rows ) ? src [ src_offset + ( sy0 + 1 ) * srcStep + sx0 ] : ( float4 ) 0 ; <nl> + v3 = ( sx0 + 1 > = 0 & & sx0 + 1 < src_cols & & sy0 + 1 > = 0 & & sy0 + 1 < src_rows ) ? src [ src_offset + ( sy0 + 1 ) * srcStep + sx0 + 1 ] : ( float4 ) 0 ; <nl> <nl> float tab [ 4 ] ; <nl> float taby [ 2 ] , tabx [ 2 ] ; <nl> __kernel void warpAffineLinear_C4_D5 ( __global float4 * src , __global float4 * ds <nl> sum + = v0 * tab [ 0 ] + v1 * tab [ 1 ] + v2 * tab [ 2 ] + v3 * tab [ 3 ] ; <nl> if ( dx > = 0 & & dx < dst_cols & & dy > = 0 & & dy < dst_rows ) <nl> dst [ dst_offset + dy * dstStep + dx ] = sum ; <nl> - } <nl> + } <nl> } <nl> <nl> __kernel void warpAffineCubic_C4_D5 ( __global float4 * src , __global float4 * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpAffineCubic_C4_D5 ( __global float4 * src , __global float4 * dst <nl> int i ; <nl> <nl> for ( i = 0 ; i < 16 ; i + + ) <nl> - v [ i ] = ( sx + ( i & 3 ) > = 0 & & sx + ( i & 3 ) < src_cols & & sy + ( i > > 2 ) > = 0 & & sy + ( i > > 2 ) < src_rows ) ? src [ src_offset + ( sy + ( i > > 2 ) ) * srcStep + ( sx + ( i & 3 ) ) ] : 0 ; <nl> + v [ i ] = ( sx + ( i & 3 ) > = 0 & & sx + ( i & 3 ) < src_cols & & sy + ( i > > 2 ) > = 0 & & sy + ( i > > 2 ) < src_rows ) ? src [ src_offset + ( sy + ( i > > 2 ) ) * srcStep + ( sx + ( i & 3 ) ) ] : ( float4 ) 0 ; <nl> <nl> float tab [ 16 ] ; <nl> float tab1y [ 4 ] , tab1x [ 4 ] ; <nl> __kernel void warpAffineCubic_C4_D5 ( __global float4 * src , __global float4 * dst <nl> dst [ dst_offset + dy * dstStep + dx ] = sum ; <nl> <nl> } <nl> - } <nl> + } <nl> } <nl> mmm a / modules / ocl / src / opencl / imgproc_warpPerspective . cl <nl> ppp b / modules / ocl / src / opencl / imgproc_warpPerspective . cl <nl> <nl> / / wrapPerspective kernel <nl> / / support data types : CV_8UC1 , CV_8UC4 , CV_32FC1 , CV_32FC4 , and three interpolation methods : NN , Linear , Cubic . <nl> <nl> - # if defined DOUBLE_SUPPORT <nl> + # if defined ( DOUBLE_SUPPORT ) <nl> + # ifdef cl_khr_fp64 <nl> # pragma OPENCL EXTENSION cl_khr_fp64 : enable <nl> + # elif defined ( cl_amd_fp64 ) <nl> + # pragma OPENCL EXTENSION cl_amd_fp64 : enable <nl> + # endif <nl> typedef double F ; <nl> typedef double4 F4 ; <nl> # define convert_F4 convert_double4 <nl> inline void interpolateCubic ( float x , float * coeffs ) <nl> / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 8UC1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> __kernel void warpPerspectiveNN_C1_D0 ( __global uchar const * restrict src , __global uchar * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveNN_C1_D0 ( __global uchar const * restrict src , __glo <nl> sval . s1 = scon . s1 ? src [ spos . s1 ] : 0 ; <nl> sval . s2 = scon . s2 ? src [ spos . s2 ] : 0 ; <nl> sval . s3 = scon . s3 ? src [ spos . s3 ] : 0 ; <nl> - dval = convert_uchar4 ( dcon ! = 0 ) ? sval : dval ; <nl> + dval = convert_uchar4 ( dcon ) ! = ( uchar4 ) ( 0 , 0 , 0 , 0 ) ? sval : dval ; <nl> * d = dval ; <nl> } <nl> } <nl> <nl> __kernel void warpPerspectiveLinear_C1_D0 ( __global const uchar * restrict src , __global uchar * dst , <nl> - int src_cols , int src_rows , int dst_cols , int dst_rows , int srcStep , <nl> - int dstStep , int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int src_cols , int src_rows , int dst_cols , int dst_rows , int srcStep , <nl> + int dstStep , int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveLinear_C1_D0 ( __global const uchar * restrict src , _ <nl> int i ; <nl> # pragma unroll 4 <nl> for ( i = 0 ; i < 4 ; i + + ) <nl> - v [ i ] = ( sx + ( i & 1 ) > = 0 & & sx + ( i & 1 ) < src_cols & & sy + ( i > > 1 ) > = 0 & & sy + ( i > > 1 ) < src_rows ) ? src [ src_offset + ( sy + ( i > > 1 ) ) * srcStep + ( sx + ( i & 1 ) ) ] : 0 ; <nl> + v [ i ] = ( sx + ( i & 1 ) > = 0 & & sx + ( i & 1 ) < src_cols & & sy + ( i > > 1 ) > = 0 & & sy + ( i > > 1 ) < src_rows ) ? src [ src_offset + ( sy + ( i > > 1 ) ) * srcStep + ( sx + ( i & 1 ) ) ] : ( uchar ) 0 ; <nl> <nl> short itab [ 4 ] ; <nl> float tab1y [ 2 ] , tab1x [ 2 ] ; <nl> __kernel void warpPerspectiveLinear_C1_D0 ( __global const uchar * restrict src , _ <nl> } <nl> <nl> __kernel void warpPerspectiveCubic_C1_D0 ( __global uchar * src , __global uchar * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveCubic_C1_D0 ( __global uchar * src , __global uchar * <nl> short ay = ( short ) ( Y & ( INTER_TAB_SIZE - 1 ) ) ; <nl> short ax = ( short ) ( X & ( INTER_TAB_SIZE - 1 ) ) ; <nl> <nl> - uchar v [ 16 ] ; <nl> + uchar v [ 16 ] ; <nl> int i , j ; <nl> <nl> # pragma unroll 4 <nl> for ( i = 0 ; i < 4 ; i + + ) <nl> - for ( j = 0 ; j < 4 ; j + + ) <nl> - { <nl> - v [ i * 4 + j ] = ( sx + j > = 0 & & sx + j < src_cols & & sy + i > = 0 & & sy + i < src_rows ) ? src [ src_offset + ( sy + i ) * srcStep + ( sx + j ) ] : 0 ; <nl> - } <nl> + for ( j = 0 ; j < 4 ; j + + ) <nl> + { <nl> + v [ i * 4 + j ] = ( sx + j > = 0 & & sx + j < src_cols & & sy + i > = 0 & & sy + i < src_rows ) ? src [ src_offset + ( sy + i ) * srcStep + ( sx + j ) ] : ( uchar ) 0 ; <nl> + } <nl> <nl> short itab [ 16 ] ; <nl> float tab1y [ 4 ] , tab1x [ 4 ] ; <nl> __kernel void warpPerspectiveCubic_C1_D0 ( __global uchar * src , __global uchar * <nl> if ( itab [ ( k1 < < 2 ) + k2 ] < itab [ ( mk1 < < 2 ) + mk2 ] ) <nl> mk1 = k1 , mk2 = k2 ; <nl> else if ( itab [ ( k1 < < 2 ) + k2 ] > itab [ ( Mk1 < < 2 ) + Mk2 ] ) <nl> - Mk1 = k1 , Mk2 = k2 ; <nl> + Mk1 = k1 , Mk2 = k2 ; <nl> } <nl> diff < 0 ? ( itab [ ( Mk1 < < 2 ) + Mk2 ] = ( short ) ( itab [ ( Mk1 < < 2 ) + Mk2 ] - diff ) ) : ( itab [ ( mk1 < < 2 ) + mk2 ] = ( short ) ( itab [ ( mk1 < < 2 ) + mk2 ] - diff ) ) ; <nl> } <nl> __kernel void warpPerspectiveCubic_C1_D0 ( __global uchar * src , __global uchar * <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> __kernel void warpPerspectiveNN_C4_D0 ( __global uchar4 const * restrict src , __global uchar4 * dst , <nl> - int src_cols , int src_rows , int dst_cols , int dst_rows , int srcStep , <nl> - int dstStep , int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int src_cols , int src_rows , int dst_cols , int dst_rows , int srcStep , <nl> + int dstStep , int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveNN_C4_D0 ( __global uchar4 const * restrict src , __gl <nl> } <nl> <nl> __kernel void warpPerspectiveLinear_C4_D0 ( __global uchar4 const * restrict src , __global uchar4 * dst , <nl> - int src_cols , int src_rows , int dst_cols , int dst_rows , int srcStep , <nl> - int dstStep , int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int src_cols , int src_rows , int dst_cols , int dst_rows , int srcStep , <nl> + int dstStep , int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveLinear_C4_D0 ( __global uchar4 const * restrict src , <nl> <nl> int4 v0 , v1 , v2 , v3 ; <nl> <nl> - v0 = ( sx > = 0 & & sx < src_cols & & sy > = 0 & & sy < src_rows ) ? convert_int4 ( src [ src_offset + sy * srcStep + sx ] ) : 0 ; <nl> - v1 = ( sx + 1 > = 0 & & sx + 1 < src_cols & & sy > = 0 & & sy < src_rows ) ? convert_int4 ( src [ src_offset + sy * srcStep + sx + 1 ] ) : 0 ; <nl> - v2 = ( sx > = 0 & & sx < src_cols & & sy + 1 > = 0 & & sy + 1 < src_rows ) ? convert_int4 ( src [ src_offset + ( sy + 1 ) * srcStep + sx ] ) : 0 ; <nl> - v3 = ( sx + 1 > = 0 & & sx + 1 < src_cols & & sy + 1 > = 0 & & sy + 1 < src_rows ) ? convert_int4 ( src [ src_offset + ( sy + 1 ) * srcStep + sx + 1 ] ) : 0 ; <nl> + v0 = ( sx > = 0 & & sx < src_cols & & sy > = 0 & & sy < src_rows ) ? convert_int4 ( src [ src_offset + sy * srcStep + sx ] ) : ( int4 ) 0 ; <nl> + v1 = ( sx + 1 > = 0 & & sx + 1 < src_cols & & sy > = 0 & & sy < src_rows ) ? convert_int4 ( src [ src_offset + sy * srcStep + sx + 1 ] ) : ( int4 ) 0 ; <nl> + v2 = ( sx > = 0 & & sx < src_cols & & sy + 1 > = 0 & & sy + 1 < src_rows ) ? convert_int4 ( src [ src_offset + ( sy + 1 ) * srcStep + sx ] ) : ( int4 ) 0 ; <nl> + v3 = ( sx + 1 > = 0 & & sx + 1 < src_cols & & sy + 1 > = 0 & & sy + 1 < src_rows ) ? convert_int4 ( src [ src_offset + ( sy + 1 ) * srcStep + sx + 1 ] ) : ( int4 ) 0 ; <nl> <nl> int itab0 , itab1 , itab2 , itab3 ; <nl> float taby , tabx ; <nl> __kernel void warpPerspectiveLinear_C4_D0 ( __global uchar4 const * restrict src , <nl> } <nl> <nl> __kernel void warpPerspectiveCubic_C4_D0 ( __global uchar4 const * restrict src , __global uchar4 * dst , <nl> - int src_cols , int src_rows , int dst_cols , int dst_rows , int srcStep , <nl> - int dstStep , int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int src_cols , int src_rows , int dst_cols , int dst_rows , int srcStep , <nl> + int dstStep , int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveCubic_C4_D0 ( __global uchar4 const * restrict src , _ <nl> int i , j ; <nl> # pragma unroll 4 <nl> for ( i = 0 ; i < 4 ; i + + ) <nl> - for ( j = 0 ; j < 4 ; j + + ) <nl> - { <nl> - v [ i * 4 + j ] = ( sx + j > = 0 & & sx + j < src_cols & & sy + i > = 0 & & sy + i < src_rows ) ? ( src [ src_offset + ( sy + i ) * srcStep + ( sx + j ) ] ) : ( uchar4 ) 0 ; <nl> - } <nl> + for ( j = 0 ; j < 4 ; j + + ) <nl> + { <nl> + v [ i * 4 + j ] = ( sx + j > = 0 & & sx + j < src_cols & & sy + i > = 0 & & sy + i < src_rows ) ? ( src [ src_offset + ( sy + i ) * srcStep + ( sx + j ) ] ) : ( uchar4 ) 0 ; <nl> + } <nl> int itab [ 16 ] ; <nl> float tab1y [ 4 ] , tab1x [ 4 ] ; <nl> float axx , ayy ; <nl> __kernel void warpPerspectiveCubic_C4_D0 ( __global uchar4 const * restrict src , _ <nl> int diff = isum - INTER_REMAP_COEF_SCALE ; <nl> int Mk1 = 2 , Mk2 = 2 , mk1 = 2 , mk2 = 2 ; <nl> <nl> - for ( k1 = 2 ; k1 < 4 ; k1 + + ) <nl> + for ( k1 = 2 ; k1 < 4 ; k1 + + ) <nl> for ( k2 = 2 ; k2 < 4 ; k2 + + ) <nl> { <nl> <nl> if ( itab [ ( k1 < < 2 ) + k2 ] < itab [ ( mk1 < < 2 ) + mk2 ] ) <nl> mk1 = k1 , mk2 = k2 ; <nl> else if ( itab [ ( k1 < < 2 ) + k2 ] > itab [ ( Mk1 < < 2 ) + Mk2 ] ) <nl> - Mk1 = k1 , Mk2 = k2 ; <nl> + Mk1 = k1 , Mk2 = k2 ; <nl> } <nl> <nl> diff < 0 ? ( itab [ ( Mk1 < < 2 ) + Mk2 ] = ( short ) ( itab [ ( Mk1 < < 2 ) + Mk2 ] - diff ) ) : ( itab [ ( mk1 < < 2 ) + mk2 ] = ( short ) ( itab [ ( mk1 < < 2 ) + mk2 ] - diff ) ) ; <nl> __kernel void warpPerspectiveCubic_C4_D0 ( __global uchar4 const * restrict src , _ <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> __kernel void warpPerspectiveNN_C1_D5 ( __global float * src , __global float * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveNN_C1_D5 ( __global float * src , __global float * dst <nl> } <nl> <nl> __kernel void warpPerspectiveLinear_C1_D5 ( __global float * src , __global float * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveLinear_C1_D5 ( __global float * src , __global float * <nl> <nl> float v0 , v1 , v2 , v3 ; <nl> <nl> - v0 = ( sx > = 0 & & sx < src_cols & & sy > = 0 & & sy < src_rows ) ? src [ src_offset + sy * srcStep + sx ] : 0 ; <nl> - v1 = ( sx + 1 > = 0 & & sx + 1 < src_cols & & sy > = 0 & & sy < src_rows ) ? src [ src_offset + sy * srcStep + sx + 1 ] : 0 ; <nl> - v2 = ( sx > = 0 & & sx < src_cols & & sy + 1 > = 0 & & sy + 1 < src_rows ) ? src [ src_offset + ( sy + 1 ) * srcStep + sx ] : 0 ; <nl> - v3 = ( sx + 1 > = 0 & & sx + 1 < src_cols & & sy + 1 > = 0 & & sy + 1 < src_rows ) ? src [ src_offset + ( sy + 1 ) * srcStep + sx + 1 ] : 0 ; <nl> + v0 = ( sx > = 0 & & sx < src_cols & & sy > = 0 & & sy < src_rows ) ? src [ src_offset + sy * srcStep + sx ] : ( float ) 0 ; <nl> + v1 = ( sx + 1 > = 0 & & sx + 1 < src_cols & & sy > = 0 & & sy < src_rows ) ? src [ src_offset + sy * srcStep + sx + 1 ] : ( float ) 0 ; <nl> + v2 = ( sx > = 0 & & sx < src_cols & & sy + 1 > = 0 & & sy + 1 < src_rows ) ? src [ src_offset + ( sy + 1 ) * srcStep + sx ] : ( float ) 0 ; <nl> + v3 = ( sx + 1 > = 0 & & sx + 1 < src_cols & & sy + 1 > = 0 & & sy + 1 < src_rows ) ? src [ src_offset + ( sy + 1 ) * srcStep + sx + 1 ] : ( float ) 0 ; <nl> <nl> float tab [ 4 ] ; <nl> float taby [ 2 ] , tabx [ 2 ] ; <nl> __kernel void warpPerspectiveLinear_C1_D5 ( __global float * src , __global float * <nl> } <nl> <nl> __kernel void warpPerspectiveCubic_C1_D5 ( __global float * src , __global float * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveCubic_C1_D5 ( __global float * src , __global float * <nl> int i ; <nl> <nl> for ( i = 0 ; i < 16 ; i + + ) <nl> - v [ i ] = ( sx + ( i & 3 ) > = 0 & & sx + ( i & 3 ) < src_cols & & sy + ( i > > 2 ) > = 0 & & sy + ( i > > 2 ) < src_rows ) ? src [ src_offset + ( sy + ( i > > 2 ) ) * srcStep + ( sx + ( i & 3 ) ) ] : 0 ; <nl> + v [ i ] = ( sx + ( i & 3 ) > = 0 & & sx + ( i & 3 ) < src_cols & & sy + ( i > > 2 ) > = 0 & & sy + ( i > > 2 ) < src_rows ) ? src [ src_offset + ( sy + ( i > > 2 ) ) * srcStep + ( sx + ( i & 3 ) ) ] : ( float ) 0 ; <nl> <nl> float tab [ 16 ] ; <nl> float tab1y [ 4 ] , tab1x [ 4 ] ; <nl> __kernel void warpPerspectiveCubic_C1_D5 ( __global float * src , __global float * <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> __kernel void warpPerspectiveNN_C4_D5 ( __global float4 * src , __global float4 * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveNN_C4_D5 ( __global float4 * src , __global float4 * d <nl> short sy = ( short ) Y ; <nl> <nl> if ( dx > = 0 & & dx < dst_cols & & dy > = 0 & & dy < dst_rows ) <nl> - dst [ ( dst_offset > > 4 ) + dy * ( dstStep > > 2 ) + dx ] = ( sx > = 0 & & sx < src_cols & & sy > = 0 & & sy < src_rows ) ? src [ ( src_offset > > 4 ) + sy * ( srcStep > > 2 ) + sx ] : 0 ; <nl> + dst [ ( dst_offset > > 4 ) + dy * ( dstStep > > 2 ) + dx ] = ( sx > = 0 & & sx < src_cols & & sy > = 0 & & sy < src_rows ) ? src [ ( src_offset > > 4 ) + sy * ( srcStep > > 2 ) + sx ] : ( float ) 0 ; <nl> } <nl> } <nl> <nl> __kernel void warpPerspectiveLinear_C4_D5 ( __global float4 * src , __global float4 * dst , int src_cols , int src_rows , <nl> - int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> - int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int dst_cols , int dst_rows , int srcStep , int dstStep , <nl> + int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveLinear_C4_D5 ( __global float4 * src , __global float4 <nl> <nl> float4 v0 , v1 , v2 , v3 ; <nl> <nl> - v0 = ( sx0 > = 0 & & sx0 < src_cols & & sy0 > = 0 & & sy0 < src_rows ) ? src [ src_offset + sy0 * srcStep + sx0 ] : 0 ; <nl> - v1 = ( sx0 + 1 > = 0 & & sx0 + 1 < src_cols & & sy0 > = 0 & & sy0 < src_rows ) ? src [ src_offset + sy0 * srcStep + sx0 + 1 ] : 0 ; <nl> - v2 = ( sx0 > = 0 & & sx0 < src_cols & & sy0 + 1 > = 0 & & sy0 + 1 < src_rows ) ? src [ src_offset + ( sy0 + 1 ) * srcStep + sx0 ] : 0 ; <nl> - v3 = ( sx0 + 1 > = 0 & & sx0 + 1 < src_cols & & sy0 + 1 > = 0 & & sy0 + 1 < src_rows ) ? src [ src_offset + ( sy0 + 1 ) * srcStep + sx0 + 1 ] : 0 ; <nl> + v0 = ( sx0 > = 0 & & sx0 < src_cols & & sy0 > = 0 & & sy0 < src_rows ) ? src [ src_offset + sy0 * srcStep + sx0 ] : ( float4 ) 0 ; <nl> + v1 = ( sx0 + 1 > = 0 & & sx0 + 1 < src_cols & & sy0 > = 0 & & sy0 < src_rows ) ? src [ src_offset + sy0 * srcStep + sx0 + 1 ] : ( float4 ) 0 ; <nl> + v2 = ( sx0 > = 0 & & sx0 < src_cols & & sy0 + 1 > = 0 & & sy0 + 1 < src_rows ) ? src [ src_offset + ( sy0 + 1 ) * srcStep + sx0 ] : ( float4 ) 0 ; <nl> + v3 = ( sx0 + 1 > = 0 & & sx0 + 1 < src_cols & & sy0 + 1 > = 0 & & sy0 + 1 < src_rows ) ? src [ src_offset + ( sy0 + 1 ) * srcStep + sx0 + 1 ] : ( float4 ) 0 ; <nl> <nl> float tab [ 4 ] ; <nl> float taby [ 2 ] , tabx [ 2 ] ; <nl> __kernel void warpPerspectiveLinear_C4_D5 ( __global float4 * src , __global float4 <nl> } <nl> <nl> __kernel void warpPerspectiveCubic_C4_D5 ( __global float4 * src , __global float4 * dst , <nl> - int src_cols , int src_rows , int dst_cols , int dst_rows , int srcStep , <nl> - int dstStep , int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> + int src_cols , int src_rows , int dst_cols , int dst_rows , int srcStep , <nl> + int dstStep , int src_offset , int dst_offset , __constant F * M , int threadCols ) <nl> { <nl> int dx = get_global_id ( 0 ) ; <nl> int dy = get_global_id ( 1 ) ; <nl> __kernel void warpPerspectiveCubic_C4_D5 ( __global float4 * src , __global float4 <nl> int i ; <nl> <nl> for ( i = 0 ; i < 16 ; i + + ) <nl> - v [ i ] = ( sx + ( i & 3 ) > = 0 & & sx + ( i & 3 ) < src_cols & & sy + ( i > > 2 ) > = 0 & & sy + ( i > > 2 ) < src_rows ) ? src [ src_offset + ( sy + ( i > > 2 ) ) * srcStep + ( sx + ( i & 3 ) ) ] : 0 ; <nl> + v [ i ] = ( sx + ( i & 3 ) > = 0 & & sx + ( i & 3 ) < src_cols & & sy + ( i > > 2 ) > = 0 & & sy + ( i > > 2 ) < src_rows ) ? src [ src_offset + ( sy + ( i > > 2 ) ) * srcStep + ( sx + ( i & 3 ) ) ] : ( float4 ) 0 ; <nl> <nl> float tab [ 16 ] ; <nl> float tab1y [ 4 ] , tab1x [ 4 ] ; <nl> __kernel void warpPerspectiveCubic_C4_D5 ( __global float4 * src , __global float4 <nl> dst [ dst_offset + dy * dstStep + dx ] = sum ; <nl> <nl> } <nl> - } <nl> + } <nl> } <nl> + <nl> mmm a / modules / ocl / src / opencl / match_template . cl <nl> ppp b / modules / ocl / src / opencl / match_template . cl <nl> void matchTemplate_Naive_CCORR_C1_D0 <nl> __global const uchar * tpl_ptr = tpl + mad24 ( i , tpl_step , tpl_offset ) ; <nl> for ( j = 0 ; j < tpl_cols ; j + + ) <nl> { <nl> - sum = mad24 ( img_ptr [ j ] , tpl_ptr [ j ] , sum ) ; <nl> + sum = mad24 ( convert_int ( img_ptr [ j ] ) , convert_int ( tpl_ptr [ j ] ) , sum ) ; <nl> } <nl> } <nl> - res [ res_idx ] = sum ; <nl> + res [ res_idx ] = ( float ) sum ; <nl> } <nl> } <nl> <nl> void matchTemplate_Naive_CCORR_C4_D0 <nl> sum = mad24 ( convert_int4 ( img_ptr [ j ] ) , convert_int4 ( tpl_ptr [ j ] ) , sum ) ; <nl> } <nl> } <nl> - res [ res_idx ] = sum . x + sum . y + sum . z + sum . w ; <nl> + res [ res_idx ] = ( float ) ( sum . x + sum . y + sum . z + sum . w ) ; <nl> } <nl> } <nl> <nl> void matchTemplate_Prepared_CCOFF_C1_D0 <nl> <nl> if ( gidx < res_cols & & gidy < res_rows ) <nl> { <nl> - float sum = ( float ) ( <nl> - ( img_sums [ SUMS_PTR ( tpl_cols , tpl_rows ) ] - img_sums [ SUMS_PTR ( tpl_cols , 0 ) ] ) <nl> - - ( img_sums [ SUMS_PTR ( 0 , tpl_rows ) ] - img_sums [ SUMS_PTR ( 0 , 0 ) ] ) ) ; <nl> + float sum = ( float ) ( ( img_sums [ SUMS_PTR ( tpl_cols , tpl_rows ) ] - img_sums [ SUMS_PTR ( tpl_cols , 0 ) ] ) <nl> + - ( img_sums [ SUMS_PTR ( 0 , tpl_rows ) ] - img_sums [ SUMS_PTR ( 0 , 0 ) ] ) ) ; <nl> res [ res_idx ] - = sum * tpl_sum ; <nl> } <nl> } <nl>
Merge pull request from bitwangyaoyao : 2 . 4_mac
opencv/opencv
36028bd8adffff62fe721f9c0e6602fde62a69db
2013-04-12T10:59:45Z
mmm a / buildscripts / smoke . py <nl> ppp b / buildscripts / smoke . py <nl> def _start ( self , argv ) : <nl> child processes of this process can be killed with a single <nl> call to TerminateJobObject ( see self . stop ( ) ) . <nl> " " " <nl> - proc = Popen ( argv ) <nl> <nl> if os . sys . platform = = " win32 " : <nl> # Create a job object with the " kill on job close " <nl> def _start ( self , argv ) : <nl> # rather than orphaning the mongod . <nl> import win32job <nl> <nl> + # Magic number needed to allow job reassignment in Windows 7 <nl> + # see : MSDN - Process Creation Flags - ms684863 <nl> + CREATE_BREAKAWAY_FROM_JOB = 0x01000000 <nl> + <nl> + proc = Popen ( argv , creationflags = CREATE_BREAKAWAY_FROM_JOB ) <nl> + <nl> self . job_object = win32job . CreateJobObject ( None , ' ' ) <nl> <nl> job_info = win32job . QueryInformationJobObject ( <nl> def _start ( self , argv ) : <nl> <nl> win32job . AssignProcessToJobObject ( self . job_object , proc . _handle ) <nl> <nl> + else : <nl> + proc = Popen ( argv ) <nl> + <nl> return proc <nl> <nl> def stop ( self ) : <nl>
smoke . py allow job reassignment for subprocesses on Windows 7 and above
mongodb/mongo
6f50df12631a01a1e742eee747b4e5a487af4816
2013-05-09T21:28:34Z
mmm a / src / python / turicreate / toolkits / style_transfer / style_transfer . py <nl> ppp b / src / python / turicreate / toolkits / style_transfer / style_transfer . py <nl> def get_styles ( self , style = None ) : <nl> | 3 | Height : 642 Width : 642 | <nl> + mmmmmm - + mmmmmmmmmmmmmmmmmmmmmmmm - - + <nl> " " " <nl> - <nl> return self . __proxy__ . get_styles ( style ) <nl> <nl> class StyleTransfer ( _CustomModel ) : <nl> mmm a / src / toolkits / style_transfer / style_transfer . cpp <nl> ppp b / src / toolkits / style_transfer / style_transfer . cpp <nl> flex_int estimate_max_iterations ( flex_int num_styles , flex_int batch_size ) { <nl> return static_cast < flex_int > ( num_styles * 10000 . 0f / batch_size ) ; <nl> } <nl> <nl> + void check_style_index ( int idx , int num_styles ) { <nl> + if ( ( idx < 0 ) | | ( idx > = num_styles ) ) <nl> + log_and_throw ( " Please choose a valid style index . " ) ; <nl> + } <nl> + <nl> } / / namespace <nl> <nl> void style_transfer : : init_options ( <nl> void style_transfer : : infer_derived_options ( ) { <nl> add_or_update_state ( { { " training_iterations " , 0 } } ) ; <nl> } <nl> <nl> + gl_sframe style_transfer : : get_styles ( variant_type style_index ) { <nl> + gl_sframe style_sf = read_state < gl_sframe > ( " styles " ) ; <nl> + gl_sarray style_filter = convert_style_indices_to_filter ( style_index ) ; <nl> + <nl> + return style_sf [ style_filter ] ; <nl> + } <nl> + <nl> + gl_sframe style_transfer : : style_sframe_with_index ( gl_sarray styles ) { <nl> + std : : vector < flexible_type > index_list ; <nl> + flex_int num_styles = read_state < flex_int > ( " num_styles " ) ; <nl> + index_list . resize ( num_styles ) ; <nl> + std : : iota ( index_list . begin ( ) , index_list . end ( ) , 0 ) ; <nl> + <nl> + return gl_sframe ( { <nl> + { " index " , index_list } , <nl> + { " style " , styles } , <nl> + } ) ; <nl> + } <nl> + <nl> + / * * <nl> + * convert_style_indices_to_filter <nl> + * <nl> + * This function takes a variant type and converts it into a boolean filter . The <nl> + * elements at the indices we want to keep are set to a value of ` 1 ` , the <nl> + * elements we don ' t want to keep are set to a value of ` 0 ` . <nl> + * / <nl> + gl_sarray style_transfer : : convert_style_indices_to_filter ( <nl> + const variant_type & data ) { <nl> + / / read the ` num_styles ` <nl> + flex_int num_styles = read_state < flex_int > ( " num_styles " ) ; <nl> + if ( variant_is < flex_list > ( data ) | | variant_is < flex_vec > ( data ) ) { <nl> + / / if the type is ` flex_list ` or ` flex_vec ` create a vector where every <nl> + / / element is set to zero <nl> + std : : vector < flexible_type > index_filter ( num_styles , 0 ) ; <nl> + flex_list index_list = variant_get_value < flex_list > ( data ) ; <nl> + / / Assert that the list is not zero - length <nl> + ASSERT_NE ( index_list . size ( ) , 0 ) ; <nl> + <nl> + / / populate the indices that are selected by the flex_list <nl> + std : : for_each ( <nl> + index_list . begin ( ) , index_list . end ( ) , <nl> + [ & index_filter , num_styles ] ( flexible_type & ft ) { <nl> + / / assert if the type is an integer or a float <nl> + ASSERT_TRUE ( ft . get_type ( ) = = flex_type_enum : : INTEGER | | <nl> + ft . get_type ( ) = = flex_type_enum : : FLOAT ) ; <nl> + <nl> + / / parse the float or integer value based on the type and , <nl> + / / set the value at the indices to 1 indicating the filter <nl> + / / to be true . <nl> + switch ( ft . get_type ( ) ) { <nl> + case flex_type_enum : : INTEGER : { <nl> + flex_int idx = ft . get < flex_int > ( ) ; <nl> + check_style_index ( idx , num_styles ) ; <nl> + index_filter [ idx ] = 1 ; <nl> + } <nl> + case flex_type_enum : : FLOAT : { <nl> + int idx = static_cast < int > ( ft . get < flex_float > ( ) ) ; <nl> + check_style_index ( idx , num_styles ) ; <nl> + index_filter [ idx ] = 1 ; <nl> + break ; <nl> + } <nl> + default : <nl> + log_and_throw ( <nl> + " Invalid data type ! The ` style ` list should contain either " <nl> + " integer or float values ! " ) ; <nl> + } <nl> + } ) ; <nl> + return index_filter ; <nl> + } else if ( variant_is < flex_int > ( data ) ) { <nl> + / / Set the index filter to zeros , set to the length of the style sframe <nl> + std : : vector < flexible_type > index_filter ( num_styles , 0 ) ; <nl> + flex_int idx = variant_get_value < flex_int > ( data ) ; <nl> + / / Check if the index is out of range or not <nl> + check_style_index ( idx , num_styles ) ; <nl> + / / Set the value at the index to ` 1 ` <nl> + index_filter [ idx ] = 1 ; <nl> + return index_filter ; <nl> + } else if ( variant_is < flex_undefined > ( data ) ) { <nl> + / / If undefined set the value to all of the styles in the sframe to 1 . Or <nl> + / / run stylize on all elements of the ` SFrame ` <nl> + return std : : vector < flexible_type > ( num_styles , 1 ) ; <nl> + } else { <nl> + log_and_throw ( <nl> + " Invalid data type ! Expect ` list ` , ` integer ` , or " <nl> + " ` None ` types ! " ) ; <nl> + } <nl> + } <nl> + <nl> gl_sframe style_transfer : : predict ( variant_type data , <nl> std : : map < std : : string , flexible_type > opts ) { <nl> gl_sframe_writer result ( { " style_idx " , " stylized_image " } , <nl> void style_transfer : : perform_predict ( gl_sarray data , gl_sframe_writer & result , <nl> { { " st_num_styles " , st_num_styles } , { " st_training " , st_train } } , <nl> weight_params ) ; <nl> <nl> - / / looping through all of the style indicies <nl> + / / looping through all of the style indices <nl> for ( size_t i : style_idx ) { <nl> std : : vector < st_example > batch = data_iter - > next_batch ( batch_size ) ; <nl> while ( ! batch . empty ( ) ) { <nl> void style_transfer : : init_train ( gl_sarray style , gl_sarray content , <nl> <nl> infer_derived_options ( ) ; <nl> <nl> - add_or_update_state ( { { " model " , " resnet - 16 " } } ) ; <nl> + add_or_update_state ( { <nl> + { " model " , " resnet - 16 " } , <nl> + { " styles " , style_sframe_with_index ( style ) } , <nl> + } ) ; <nl> <nl> m_resnet_spec = init_resnet ( resnet_mlmodel_path , num_styles ) ; <nl> m_vgg_spec = init_vgg_16 ( vgg_mlmodel_path ) ; <nl> mmm a / src / toolkits / style_transfer / style_transfer . hpp <nl> ppp b / src / toolkits / style_transfer / style_transfer . hpp <nl> class EXPORT style_transfer : public ml_model_base { <nl> gl_sframe predict ( variant_type data , <nl> std : : map < std : : string , flexible_type > opts ) ; <nl> <nl> + gl_sframe get_styles ( variant_type style_index ) ; <nl> + <nl> void import_from_custom_model ( variant_map_type model_data , size_t version ) ; <nl> <nl> BEGIN_CLASS_MEMBER_REGISTRATION ( " style_transfer " ) <nl> class EXPORT style_transfer : public ml_model_base { <nl> REGISTER_CLASS_MEMBER_FUNCTION ( style_transfer : : import_from_custom_model , <nl> " model_data " , " version " ) ; <nl> <nl> + REGISTER_CLASS_MEMBER_FUNCTION ( style_transfer : : get_styles , " style_index " ) ; <nl> + register_defaults ( " get_styles " , { { " style_index " , FLEX_UNDEFINED } } ) ; <nl> + <nl> END_CLASS_MEMBER_REGISTRATION <nl> <nl> protected : <nl> class EXPORT style_transfer : public ml_model_base { <nl> <nl> static gl_sarray convert_types_to_sarray ( const variant_type & data ) ; <nl> <nl> + / * * <nl> + * convert_style_indices_to_filter <nl> + * <nl> + * This function takes a variant type and converts it into a boolean filter . <nl> + * The elements at the indices we want to keep are set to a value of ` 1 ` , the <nl> + * elements we don ' t want to keep are set to a value of ` 0 ` . <nl> + * / <nl> + gl_sarray convert_style_indices_to_filter ( const variant_type & data ) ; <nl> + gl_sframe style_sframe_with_index ( gl_sarray styles ) ; <nl> + <nl> flex_int get_max_iterations ( ) const ; <nl> flex_int get_training_iterations ( ) const ; <nl> flex_int get_num_classes ( ) const ; <nl>
Style transfer get_styles c + + ( )
apple/turicreate
6f98c51b0fd3b21e865bc596fde6cea5fe582db3
2019-11-12T20:52:23Z
mmm a / source / common / thread_local / thread_local_impl . cc <nl> ppp b / source / common / thread_local / thread_local_impl . cc <nl> <nl> # include " common / thread_local / thread_local_impl . h " <nl> <nl> + # include < algorithm > <nl> # include < atomic > <nl> # include < cstdint > <nl> # include < list > <nl> SlotPtr InstanceImpl : : allocateSlot ( ) { <nl> ASSERT ( std : : this_thread : : get_id ( ) = = main_thread_id_ ) ; <nl> ASSERT ( ! shutdown_ ) ; <nl> <nl> - for ( uint64_t i = 0 ; i < slots_ . size ( ) ; i + + ) { <nl> - if ( slots_ [ i ] = = nullptr ) { <nl> - std : : unique_ptr < SlotImpl > slot ( new SlotImpl ( * this , i ) ) ; <nl> - slots_ [ i ] = slot . get ( ) ; <nl> - return slot ; <nl> - } <nl> + if ( free_slot_indexes_ . empty ( ) ) { <nl> + std : : unique_ptr < SlotImpl > slot ( new SlotImpl ( * this , slots_ . size ( ) ) ) ; <nl> + slots_ . push_back ( slot . get ( ) ) ; <nl> + return slot ; <nl> } <nl> - <nl> - std : : unique_ptr < SlotImpl > slot ( new SlotImpl ( * this , slots_ . size ( ) ) ) ; <nl> - slots_ . push_back ( slot . get ( ) ) ; <nl> + const uint32_t idx = free_slot_indexes_ . front ( ) ; <nl> + free_slot_indexes_ . pop_front ( ) ; <nl> + ASSERT ( idx < slots_ . size ( ) ) ; <nl> + std : : unique_ptr < SlotImpl > slot ( new SlotImpl ( * this , idx ) ) ; <nl> + slots_ [ idx ] = slot . get ( ) ; <nl> return slot ; <nl> } <nl> <nl> void InstanceImpl : : removeSlot ( SlotImpl & slot ) { <nl> <nl> const uint64_t index = slot . index_ ; <nl> slots_ [ index ] = nullptr ; <nl> + ASSERT ( std : : find ( free_slot_indexes_ . begin ( ) , free_slot_indexes_ . end ( ) , index ) = = <nl> + free_slot_indexes_ . end ( ) , <nl> + fmt : : format ( " slot index { } already in free slot set ! " , index ) ) ; <nl> + free_slot_indexes_ . push_back ( index ) ; <nl> runOnAllThreads ( [ index ] ( ) - > void { <nl> / / This runs on each thread and clears the slot , making it available for a new allocations . <nl> / / This is safe even if a new allocation comes in , because everything happens with post ( ) and <nl> mmm a / source / common / thread_local / thread_local_impl . h <nl> ppp b / source / common / thread_local / thread_local_impl . h <nl> class InstanceImpl : Logger : : Loggable < Logger : : Id : : main > , public Instance { <nl> <nl> static thread_local ThreadLocalData thread_local_data_ ; <nl> std : : vector < SlotImpl * > slots_ ; <nl> + / / A list of index of freed slots . <nl> + std : : list < uint32_t > free_slot_indexes_ ; <nl> + <nl> std : : list < std : : reference_wrapper < Event : : Dispatcher > > registered_threads_ ; <nl> std : : thread : : id main_thread_id_ ; <nl> Event : : Dispatcher * main_thread_dispatcher_ { } ; <nl>
tls : maintain a free slot index set in TLS InstanceImpl to allocate in O ( 1 … ( )
envoyproxy/envoy
87c38e1cd8bc7804ad07de276ffbb7c2d57c0404
2019-08-21T20:12:12Z
mmm a / Code / CryEngine / CryAISystem / Navigation / MNM / TileGenerator . cpp <nl> ppp b / Code / CryEngine / CryAISystem / Navigation / MNM / TileGenerator . cpp <nl> static uchar s_CornerTable [ 3 ] [ 3 ] [ 3 ] = <nl> / / * INDENT - ON * - disable uncrustify ' s indenting , as I want to preserve specific comment formatting . <nl> } ; <nl> <nl> + namespace PinchCornerTable <nl> + { <nl> + <nl> + enum EBitMask : uint8 <nl> + { <nl> + eExt = BIT ( 0 ) , / / ! < pinch point on external contour <nl> + eInt = BIT ( 1 ) / / ! < pinch point on internal contour <nl> + } ; <nl> + <nl> / / Pinch corner table is used to detect unremovable pinch points on external contours <nl> / / using neighbour classes . <nl> / / Indexing order : left , front - left , front . <nl> / / TODO pavloi 2016 . 03 . 21 : s_CornerTable and s_PinchCornerTable can be merged together ( bitmask ) . <nl> - / / TODO pavloi 2016 . 03 . 22 : s_PinchCornerTable doesn ' t work on internal ( hole ) contours properly . <nl> - static const uchar s_PinchCornerTable [ 3 ] [ 3 ] [ 3 ] = <nl> + static const uint8 s_PinchCornerTable [ 3 ] [ 3 ] [ 3 ] = <nl> { <nl> / / * INDENT - OFF * - disable uncrustify ' s indenting , as I want to preserve specific comment formatting . <nl> { / / UW <nl> - / / UW , NB , WB <nl> - { 0 , 0 , 0 } , / / UW <nl> - { 1 , 0 , 1 } , / / NB <nl> - { 1 , 0 , 0 } , / / WB <nl> + / / UW , NB , WB <nl> + { 0 , 0 , 0 } , / / UW <nl> + { eExt | eInt , 0 , eExt } , / / NB <nl> + { eExt | eInt , eInt , 0 } , / / WB <nl> } , <nl> { / / NB <nl> - / / UW , NB , WB <nl> - { 0 , 0 , 0 } , / / UW <nl> - { 0 , 0 , 0 } , / / NB <nl> - { 0 , 0 , 0 } , / / WB <nl> + / / UW , NB , WB <nl> + { 0 , eInt , 0 } , / / UW <nl> + { 0 , 0 , 0 } , / / NB <nl> + { eInt , eInt , 0 } , / / WB <nl> } , <nl> { / / WB <nl> - / / UW , NB , WB <nl> - { 0 , 0 , 1 } , / / UW <nl> - { 1 , 0 , 1 } , / / NB <nl> - { 0 , 0 , 0 } , / / WB <nl> + / / UW , NB , WB <nl> + { 0 , 0 , eExt } , / / UW <nl> + { eExt , 0 , eExt } , / / NB <nl> + { 0 , 0 , 0 } , / / WB <nl> } , <nl> / / * INDENT - ON * - disable uncrustify ' s indenting , as I want to preserve specific comment formatting . <nl> } ; <nl> <nl> + } <nl> + <nl> / * static * / size_t TileGenerator : : BorderSizeH ( const Params & params ) <nl> { <nl> / / TODO pavloi 2016 . 03 . 16 : inclineTestCount = ( height + 1 ) comes from FilterWalkable <nl> struct TileGenerator : : SFilterWalkableParams <nl> <nl> struct TileGenerator : : SSpanClearance <nl> { <nl> - SSpanClearance ( const SSpanCoord & spanCoord , const CompactSpanGrid : : Span & span , const CompactSpanGrid : : Cell cell , const TileGenerator : : SFilterWalkableParams & filterParams , const CompactSpanGrid & spanGrid ) <nl> + SSpanClearance ( const SSpanCoord & spanCoord , const CompactSpanGrid : : Span & span , const CompactSpanGrid : : Cell & cell , const TileGenerator : : SFilterWalkableParams & filterParams , const CompactSpanGrid & spanGrid ) <nl> { <nl> top = span . bottom + span . height ; <nl> nextBottom = filterParams . spaceTop ; <nl> bool TileGenerator : : GatherSurroundingInfo ( const Vec2i & vertex , const Vec2i & dire <nl> } <nl> <nl> void TileGenerator : : DetermineContourVertex ( const Vec2i & vertex , const Vec2i & direction , const uint16 top , <nl> - const uint16 climbableVoxelCount , ContourVertex & contourVertex , SContourVertexDebugInfo * pDebugInfo ) const <nl> + const uint16 climbableVoxelCount , ContourVertex & contourVertex , const bool bInternalContour , SContourVertexDebugInfo * pDebugInfo ) const <nl> { <nl> const size_t xoffs = ( direction . x = = 1 ) | ( direction . y = = - 1 ) ; <nl> const size_t yoffs = ( direction . y = = 1 ) | ( direction . x = = 1 ) ; <nl> void TileGenerator : : DetermineContourVertex ( const Vec2i & vertex , const Vec2i & dir <nl> / / contour can walk into borderV span . <nl> if ( m_spanGrid . GetSpanAt ( vertex . x , vertex . y , top , climbableVoxelCount , index ) ) <nl> internalBorderV = ( m_labels [ index ] & BorderLabelV ) ! = 0 ; <nl> + <nl> + assert ( ( internalBorderV & & bInternalContour ) | | ! internalBorderV ) ; <nl> } <nl> <nl> / / NOTE pavloi 2016 . 03 . 15 : either we above lower borderV , or we ' re hitting an upper borderV . <nl> void TileGenerator : : DetermineContourVertex ( const Vec2i & vertex , const Vec2i & dir <nl> } <nl> } <nl> <nl> - if ( s_PinchCornerTable [ lclass ] [ flclass ] [ fclass ] ) <nl> + const uint8 pinchTableMask = bInternalContour ? PinchCornerTable : : eInt : PinchCornerTable : : eExt ; <nl> + if ( PinchCornerTable : : s_PinchCornerTable [ lclass ] [ flclass ] [ fclass ] & pinchTableMask ) <nl> { <nl> flags | = ContourVertex : : Unremovable ; <nl> DebugAddContourVertexUnremovableReason ( pDebugInfo , " Pinch " ) ; <nl> int TileGenerator : : LabelTracerPath ( const TileGenerator : : TracerPath & path , size_t <nl> } <nl> # endif <nl> <nl> + const bool bInternalContour = ( internalLabelFlags & InternalContour ) ! = 0 ; <nl> + <nl> / / Add a vertex at each point . <nl> - DetermineContourVertex ( Vec2i ( curr . pos ) , curr . GetDir ( ) , curr . pos . z , static_cast < uint16 > ( climbableVoxelCount ) , * & vertex , pDebugInfo ) ; <nl> + DetermineContourVertex ( Vec2i ( curr . pos ) , curr . GetDir ( ) , curr . pos . z , static_cast < uint16 > ( climbableVoxelCount ) , * & vertex , bInternalContour , pDebugInfo ) ; <nl> <nl> / / Get the paint values for the current neighbour and the next neighbour . If they don ' t match then we must have a vert . <nl> const bool bImportantVert = ( m_paint [ curr . indexOut ] ! = m_paint [ next . indexOut ] ) ; <nl> int TileGenerator : : LabelTracerPath ( const TileGenerator : : TracerPath & path , size_t <nl> { <nl> if ( ! ( vertex . flags & ContourVertex : : Unremovable ) ) <nl> { <nl> - / / TODO pavloi 2016 . 03 . 22 : so far may happen only for hole contours , <nl> - / / but I don ' t think it ' s a problem . Pinch points on external contours should <nl> - / / be properly detected using pinch contour table . <nl> - <nl> - / / CryLogAlways ( " removable pinch point , origin ( % g , % g , % g ) , tracer ( % d , % d , % d ) " , <nl> - / / m_params . origin . x , m_params . origin . y , m_params . origin . z , <nl> - / / curr . pos . x , curr . pos . y , curr . pos . z ) ; <nl> + / / NOTE pavloi 2016 . 06 . 15 : since pinch contour table works for both external and <nl> + / / internal contours , this should never happen . But just in case . <nl> + AIWarning ( " [ MNM ] TileGenerator potential issue : removable pinch point , origin ( % g , % g , % g ) , tracer ( % d , % d , % d ) " , <nl> + m_params . origin . x , m_params . origin . y , m_params . origin . z , <nl> + curr . pos . x , curr . pos . y , curr . pos . z ) ; <nl> + <nl> + vertex . flags | = ContourVertex : : Unremovable ; <nl> + DebugAddContourVertexUnremovableReason ( pDebugInfo , " next pinch " ) ; <nl> } <nl> } <nl> AddContourVertex ( vertex , region , contour ) ; <nl> bool TileGenerator : : SimplifyContour ( const Contour & contour , const real_t & tolera <nl> { <nl> const ContourVertex & v = contour [ i ] ; <nl> <nl> - if ( ( v . x < min . x ) | | ( ( v . x = = min . x ) & & ( v . y > min . y ) ) ) <nl> + if ( ( v . x < min . x ) | | ( ( v . x = = min . x ) & & ( v . y < min . y ) ) ) <nl> { <nl> minVertex = i ; <nl> min = Vec3i ( v . x , v . y , v . z ) ; <nl> } <nl> <nl> - if ( ( v . x > max . x ) | | ( ( v . x = = max . x ) & & ( v . y > min . y ) ) ) <nl> + if ( ( v . x > max . x ) | | ( ( v . x = = max . x ) & & ( v . y > max . y ) ) ) <nl> { <nl> maxVertex = i ; <nl> max = Vec3i ( v . x , v . y , v . z ) ; <nl> mmm a / Code / CryEngine / CryAISystem / Navigation / MNM / TileGenerator . h <nl> ppp b / Code / CryEngine / CryAISystem / Navigation / MNM / TileGenerator . h <nl> class TileGenerator <nl> const uint16 climbableVoxelCount , size_t & height , SurroundingSpanInfo & left , SurroundingSpanInfo & front , <nl> SurroundingSpanInfo & frontLeft ) const ; <nl> void DetermineContourVertex ( const Vec2i & vertex , const Vec2i & direction , uint16 top , <nl> - uint16 climbableVoxelCount , ContourVertex & contourVertex , SContourVertexDebugInfo * pDebugInfo ) const ; <nl> + uint16 climbableVoxelCount , ContourVertex & contourVertex , const bool bInternalContour , SContourVertexDebugInfo * pDebugInfo ) const ; <nl> inline bool ContourVertexRemovable ( const ContourVertex & contourVertex ) const <nl> { <nl> return ( ( contourVertex . flags & ContourVertex : : TileBoundary ) = = 0 ) <nl>
! XI / / ce / task_ai_mnm_fixes_and_refactoring - > / / ce / main ( Approved by achim )
CRYTEK/CRYENGINE
561e8b90ee3f867ea4f24fe6a5a67053aab1d6b6
2016-06-15T15:13:03Z
mmm a / modules / calib3d / src / stereosgbm . cpp <nl> ppp b / modules / calib3d / src / stereosgbm . cpp <nl> void cv : : filterSpeckles ( InputOutputArray _img , double _newval , int maxSpeckleSi <nl> double _maxDiff , InputOutputArray __buf ) <nl> { <nl> Mat img = _img . getMat ( ) ; <nl> + int type = img . type ( ) , cn = CV_MAT_CN ( type ) ; <nl> Mat temp , & _buf = __buf . needed ( ) ? __buf . getMatRef ( ) : temp ; <nl> - CV_Assert ( img . type ( ) = = CV_8UC1 | | img . type ( ) = = CV_16SC1 ) ; <nl> + CV_Assert ( type = = CV_8UC1 | | type = = CV_16SC1 ) ; <nl> <nl> - int newVal = cvRound ( _newval ) ; <nl> - int maxDiff = cvRound ( _maxDiff ) ; <nl> + int newVal = cvRound ( _newval ) , maxDiff = cvRound ( _maxDiff ) ; <nl> <nl> - if ( img . type ( ) = = CV_8UC1 ) <nl> + # if defined HAVE_IPP & & ! defined HAVE_IPP_ICV_ONLY <nl> + Ipp32s bufsize = 0 ; <nl> + IppiSize roisize = { img . cols , img . rows } ; <nl> + IppDataType datatype = type = = CV_8UC1 ? ipp8u : ipp16s ; <nl> + <nl> + if ( ! __buf . needed ( ) & & ippiMarkSpecklesGetBufferSize ( roisize , datatype , cn , & bufsize ) ) <nl> + { <nl> + Ipp8u * buffer = ippsMalloc_8u ( bufsize ) ; <nl> + IppStatus status = ( IppStatus ) - 1 ; <nl> + <nl> + if ( type = = CV_8UC1 ) <nl> + status = ippiMarkSpeckles_8u_C1IR ( ( Ipp8u * ) img . data , ( int ) img . step , roisize , <nl> + ( Ipp8u ) newVal , maxSpeckleSize , maxDiff , ippiNormL1 , buffer ) ; <nl> + else if ( type = = CV_16SC1 ) <nl> + status = ippiMarkSpeckles_16s_C1IR ( ( Ipp16s * ) img . data , ( int ) img . step , roisize , <nl> + ( Ipp16s ) newVal , maxSpeckleSize , maxDiff , ippiNormL1 , buffer ) ; <nl> + <nl> + printf ( " % s \ n " , ippGetStatusString ( status ) ) ; <nl> + if ( status > = 0 ) <nl> + return ; <nl> + } <nl> + # endif <nl> + <nl> + if ( type = = CV_8UC1 ) <nl> filterSpecklesImpl < uchar > ( img , newVal , maxSpeckleSize , maxDiff , _buf ) ; <nl> else <nl> filterSpecklesImpl < short > ( img , newVal , maxSpeckleSize , maxDiff , _buf ) ; <nl>
cv : : filterSpeckles
opencv/opencv
76c415ff49e43bbf4c3eabb8cffb0b089b633c0f
2014-04-21T09:14:55Z
mmm a / stdlib / public / SDK / Dispatch / Private . swift <nl> ppp b / stdlib / public / SDK / Dispatch / Private . swift <nl> public func dispatch_data_copy_region ( _ data : __DispatchData , _ location : Int , _ <nl> fatalError ( ) <nl> } <nl> <nl> - @ available ( * , unavailable , renamed : " DispatchQueue . asynchronously ( self : group : qos : flags : execute : ) " ) <nl> + @ available ( * , unavailable , renamed : " DispatchQueue . async ( self : group : qos : flags : execute : ) " ) <nl> public func dispatch_group_async ( _ group : DispatchGroup , _ queue : DispatchQueue , _ block : ( ) - > Void ) <nl> { <nl> fatalError ( ) <nl> public func dispatch_apply ( _ iterations : Int , _ queue : DispatchQueue , _ block : ( <nl> fatalError ( ) <nl> } <nl> <nl> - @ available ( * , unavailable , renamed : " DispatchQueue . asynchronously ( self : execute : ) " ) <nl> + @ available ( * , unavailable , renamed : " DispatchQueue . async ( self : execute : ) " ) <nl> public func dispatch_async ( _ queue : DispatchQueue , _ block : ( ) - > Void ) <nl> { <nl> fatalError ( ) <nl>
Merge pull request from NachoSoto / asynchronously - fixit
apple/swift
6d94756a5e6d6def22d757ff890aeb9cdfdaa486
2017-01-21T01:56:15Z
mmm a / README . md <nl> ppp b / README . md <nl> For previous versions , please read : <nl> <nl> # # V3 changes <nl> <nl> + * v3 . 0 , 2020 - 02 - 04 , For [ # 1186 ] [ bug # 1186 ] , refactor security check . 3 . 0 . 114 <nl> * v3 . 0 , 2020 - 02 - 04 , Fix [ # 939 ] [ bug # 939 ] , response right A / V flag in FLV header . 3 . 0 . 113 <nl> * v3 . 0 , 2020 - 02 - 04 , For [ # 939 ] [ bug # 939 ] , always enable fast FLV streaming . <nl> * < strong > v3 . 0 , 2020 - 02 - 02 , [ 3 . 0 beta0 ( 3 . 0 . 112 ) ] [ r3 . 0b0 ] released . 121709 lines . < / strong > <nl> Winlin <nl> [ bug # 1230 ] : https : / / github . com / ossrs / srs / issues / 1230 <nl> [ bug # 1206 ] : https : / / github . com / ossrs / srs / issues / 1206 <nl> [ bug # 939 ] : https : / / github . com / ossrs / srs / issues / 939 <nl> + [ bug # 1186 ] : https : / / github . com / ossrs / srs / issues / 1186 <nl> [ bug # xxxxxxxxxxxxx ] : https : / / github . com / ossrs / srs / issues / xxxxxxxxxxxxx <nl> <nl> [ exo # 828 ] : https : / / github . com / google / ExoPlayer / pull / 828 <nl> mmm a / trunk / src / app / srs_app_config . cpp <nl> ppp b / trunk / src / app / srs_app_config . cpp <nl> SrsConfDirective * SrsConfDirective : : get_or_create ( string n , string a0 ) <nl> if ( ! conf ) { <nl> conf = new SrsConfDirective ( ) ; <nl> conf - > name = n ; <nl> - conf - > set_arg0 ( a0 ) ; <nl> + conf - > args . push_back ( a0 ) ; <nl> directives . push_back ( conf ) ; <nl> } <nl> <nl> return conf ; <nl> } <nl> <nl> + SrsConfDirective * SrsConfDirective : : get_or_create ( string n , string a0 , string a1 ) <nl> + { <nl> + SrsConfDirective * conf = get ( n , a0 ) ; <nl> + <nl> + if ( ! conf ) { <nl> + conf = new SrsConfDirective ( ) ; <nl> + conf - > name = n ; <nl> + conf - > args . push_back ( a0 ) ; <nl> + conf - > args . push_back ( a1 ) ; <nl> + directives . push_back ( conf ) ; <nl> + } <nl> + <nl> + return conf ; <nl> + } <nl> + <nl> SrsConfDirective * SrsConfDirective : : set_arg0 ( string a0 ) <nl> { <nl> if ( arg0 ( ) = = a0 ) { <nl> mmm a / trunk / src / app / srs_app_config . hpp <nl> ppp b / trunk / src / app / srs_app_config . hpp <nl> class SrsConfDirective <nl> public : <nl> virtual SrsConfDirective * get_or_create ( std : : string n ) ; <nl> virtual SrsConfDirective * get_or_create ( std : : string n , std : : string a0 ) ; <nl> + virtual SrsConfDirective * get_or_create ( std : : string n , std : : string a0 , std : : string a1 ) ; <nl> virtual SrsConfDirective * set_arg0 ( std : : string a0 ) ; <nl> / / Remove the v from sub directives , user must free the v . <nl> virtual void remove ( SrsConfDirective * v ) ; <nl> mmm a / trunk / src / app / srs_app_security . cpp <nl> ppp b / trunk / src / app / srs_app_security . cpp <nl> SrsSecurity : : ~ SrsSecurity ( ) <nl> srs_error_t SrsSecurity : : check ( SrsRtmpConnType type , string ip , SrsRequest * req ) <nl> { <nl> srs_error_t err = srs_success ; <nl> - <nl> + <nl> / / allow all if security disabled . <nl> if ( ! _srs_config - > get_security_enabled ( req - > vhost ) ) { <nl> - return err ; <nl> + return err ; / / OK <nl> } <nl> - <nl> - / / default to deny all when security enabled . <nl> - err = srs_error_new ( ERROR_SYSTEM_SECURITY , " allowed " ) ; <nl> - <nl> + <nl> / / rules to apply <nl> SrsConfDirective * rules = _srs_config - > get_security_rules ( req - > vhost ) ; <nl> + return do_check ( rules , type , ip , req ) ; <nl> + } <nl> + <nl> + srs_error_t SrsSecurity : : do_check ( SrsConfDirective * rules , SrsRtmpConnType type , string ip , SrsRequest * req ) <nl> + { <nl> + srs_error_t err = srs_success ; <nl> + <nl> if ( ! rules ) { <nl> - return err ; <nl> + return srs_error_new ( ERROR_SYSTEM_SECURITY , " default deny for % s " , ip . c_str ( ) ) ; <nl> } <nl> - <nl> - / / allow if matches allow strategy . <nl> - if ( allow_check ( rules , type , ip ) = = ERROR_SYSTEM_SECURITY_ALLOW ) { <nl> - srs_error_reset ( err ) ; <nl> - } <nl> - <nl> + <nl> / / deny if matches deny strategy . <nl> - if ( deny_check ( rules , type , ip ) = = ERROR_SYSTEM_SECURITY_DENY ) { <nl> - srs_error_reset ( err ) ; <nl> - return srs_error_new ( ERROR_SYSTEM_SECURITY_DENY , " denied " ) ; <nl> + if ( ( err = deny_check ( rules , type , ip ) ) ! = srs_success ) { <nl> + return srs_error_wrap ( err , " for % s " , ip . c_str ( ) ) ; <nl> } <nl> <nl> + / / allow if matches allow strategy . <nl> + if ( ( err = allow_check ( rules , type , ip ) ) ! = srs_success ) { <nl> + return srs_error_wrap ( err , " for % s " , ip . c_str ( ) ) ; <nl> + } <nl> + <nl> return err ; <nl> } <nl> <nl> - int SrsSecurity : : allow_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : : string ip ) <nl> + srs_error_t SrsSecurity : : allow_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : : string ip ) <nl> { <nl> - int ret = ERROR_SUCCESS ; <nl> - <nl> + int allow_rules = 0 ; <nl> + int deny_rules = 0 ; <nl> + <nl> for ( int i = 0 ; i < ( int ) rules - > directives . size ( ) ; i + + ) { <nl> SrsConfDirective * rule = rules - > at ( i ) ; <nl> - <nl> + <nl> if ( rule - > name ! = " allow " ) { <nl> + if ( rule - > name = = " deny " ) { <nl> + deny_rules + + ; <nl> + } <nl> continue ; <nl> } <nl> - <nl> + allow_rules + + ; <nl> + <nl> switch ( type ) { <nl> case SrsRtmpConnPlay : <nl> if ( rule - > arg0 ( ) ! = " play " ) { <nl> break ; <nl> } <nl> if ( rule - > arg1 ( ) = = " all " | | rule - > arg1 ( ) = = ip ) { <nl> - ret = ERROR_SYSTEM_SECURITY_ALLOW ; <nl> - break ; <nl> + return srs_success ; / / OK <nl> } <nl> break ; <nl> case SrsRtmpConnFMLEPublish : <nl> int SrsSecurity : : allow_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : <nl> break ; <nl> } <nl> if ( rule - > arg1 ( ) = = " all " | | rule - > arg1 ( ) = = ip ) { <nl> - ret = ERROR_SYSTEM_SECURITY_ALLOW ; <nl> - break ; <nl> + return srs_success ; / / OK <nl> } <nl> break ; <nl> case SrsRtmpConnUnknown : <nl> default : <nl> break ; <nl> } <nl> - <nl> - / / when matched , donot search more . <nl> - if ( ret = = ERROR_SYSTEM_SECURITY_ALLOW ) { <nl> - break ; <nl> - } <nl> } <nl> - <nl> - return ret ; <nl> + <nl> + if ( allow_rules > 0 | | ( deny_rules + allow_rules ) = = 0 ) { <nl> + return srs_error_new ( ERROR_SYSTEM_SECURITY_ALLOW , " not allowed by any of % d rules " , allow_rules ) ; <nl> + } <nl> + return srs_success ; / / OK <nl> } <nl> <nl> - int SrsSecurity : : deny_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : : string ip ) <nl> + srs_error_t SrsSecurity : : deny_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : : string ip ) <nl> { <nl> - int ret = ERROR_SUCCESS ; <nl> - <nl> for ( int i = 0 ; i < ( int ) rules - > directives . size ( ) ; i + + ) { <nl> SrsConfDirective * rule = rules - > at ( i ) ; <nl> <nl> int SrsSecurity : : deny_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : : <nl> break ; <nl> } <nl> if ( rule - > arg1 ( ) = = " all " | | rule - > arg1 ( ) = = ip ) { <nl> - ret = ERROR_SYSTEM_SECURITY_DENY ; <nl> - break ; <nl> + return srs_error_new ( ERROR_SYSTEM_SECURITY_DENY , " deny by rule < % s > " , rule - > arg1 ( ) . c_str ( ) ) ; <nl> } <nl> break ; <nl> case SrsRtmpConnFMLEPublish : <nl> int SrsSecurity : : deny_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : : <nl> break ; <nl> } <nl> if ( rule - > arg1 ( ) = = " all " | | rule - > arg1 ( ) = = ip ) { <nl> - ret = ERROR_SYSTEM_SECURITY_DENY ; <nl> - break ; <nl> + return srs_error_new ( ERROR_SYSTEM_SECURITY_DENY , " deny by rule < % s > " , rule - > arg1 ( ) . c_str ( ) ) ; <nl> } <nl> break ; <nl> case SrsRtmpConnUnknown : <nl> default : <nl> break ; <nl> } <nl> - <nl> - / / when matched , donot search more . <nl> - if ( ret = = ERROR_SYSTEM_SECURITY_DENY ) { <nl> - break ; <nl> - } <nl> } <nl> <nl> - return ret ; <nl> + return srs_success ; / / OK <nl> } <nl> <nl> mmm a / trunk / src / app / srs_app_security . hpp <nl> ppp b / trunk / src / app / srs_app_security . hpp <nl> class SrsSecurity <nl> / / @ param req the request object of client . <nl> virtual srs_error_t check ( SrsRtmpConnType type , std : : string ip , SrsRequest * req ) ; <nl> private : <nl> - / / Security check the allow , <nl> - / / @ return , if allowed , ERROR_SYSTEM_SECURITY_ALLOW . <nl> - virtual int allow_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : : string ip ) ; <nl> - / / Security check the deny , <nl> - / / @ return , if denied , ERROR_SYSTEM_SECURITY_DENY . <nl> - virtual int deny_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : : string ip ) ; <nl> + virtual srs_error_t do_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : : string ip , SrsRequest * req ) ; <nl> + virtual srs_error_t allow_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : : string ip ) ; <nl> + virtual srs_error_t deny_check ( SrsConfDirective * rules , SrsRtmpConnType type , std : : string ip ) ; <nl> } ; <nl> <nl> # endif <nl> mmm a / trunk / src / core / srs_core_version3 . hpp <nl> ppp b / trunk / src / core / srs_core_version3 . hpp <nl> <nl> # ifndef SRS_CORE_VERSION3_HPP <nl> # define SRS_CORE_VERSION3_HPP <nl> <nl> - # define SRS_VERSION3_REVISION 113 <nl> + # define SRS_VERSION3_REVISION 114 <nl> <nl> # endif <nl> mmm a / trunk / src / utest / srs_utest_app . cpp <nl> ppp b / trunk / src / utest / srs_utest_app . cpp <nl> using namespace std ; <nl> <nl> # include < srs_kernel_error . hpp > <nl> # include < srs_app_fragment . hpp > <nl> + # include < srs_app_security . hpp > <nl> + # include < srs_app_config . hpp > <nl> <nl> # include < srs_app_st . hpp > <nl> <nl> VOID TEST ( AppFragmentTest , CheckDuration ) <nl> } <nl> } <nl> <nl> + VOID TEST ( AppSecurity , CheckSecurity ) <nl> + { <nl> + srs_error_t err ; <nl> + <nl> + / / Deny if no rules . <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; <nl> + HELPER_EXPECT_FAILED ( sec . do_check ( NULL , SrsRtmpConnUnknown , " " , & rr ) ) ; <nl> + } <nl> + <nl> + / / Deny if not allowed . <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + HELPER_EXPECT_FAILED ( sec . do_check ( & rules , SrsRtmpConnUnknown , " " , & rr ) ) ; <nl> + } <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " others " ) ; rules . get_or_create ( " any " ) ; <nl> + HELPER_EXPECT_FAILED ( sec . do_check ( & rules , SrsRtmpConnUnknown , " " , & rr ) ) ; <nl> + } <nl> + <nl> + / / Deny by rule . <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " deny " , " play " , " all " ) ; <nl> + HELPER_EXPECT_FAILED ( sec . do_check ( & rules , SrsRtmpConnPlay , " " , & rr ) ) ; <nl> + } <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " deny " , " play " , " 12 . 13 . 14 . 15 " ) ; <nl> + HELPER_EXPECT_FAILED ( sec . do_check ( & rules , SrsRtmpConnPlay , " 12 . 13 . 14 . 15 " , & rr ) ) ; <nl> + } <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " deny " , " play " , " 11 . 12 . 13 . 14 " ) ; <nl> + if ( true ) { <nl> + SrsConfDirective * d = new SrsConfDirective ( ) ; <nl> + d - > name = " deny " ; <nl> + d - > args . push_back ( " play " ) ; <nl> + d - > args . push_back ( " 12 . 13 . 14 . 15 " ) ; <nl> + rules . directives . push_back ( d ) ; <nl> + } <nl> + HELPER_EXPECT_FAILED ( sec . do_check ( & rules , SrsRtmpConnPlay , " 12 . 13 . 14 . 15 " , & rr ) ) ; <nl> + } <nl> + <nl> + / / Allowed if not denied . <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " deny " , " play " , " all " ) ; <nl> + HELPER_EXPECT_SUCCESS ( sec . do_check ( & rules , SrsRtmpConnFMLEPublish , " 12 . 13 . 14 . 15 " , & rr ) ) ; <nl> + } <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " deny " , " play " , " 12 . 13 . 14 . 15 " ) ; <nl> + HELPER_EXPECT_SUCCESS ( sec . do_check ( & rules , SrsRtmpConnFMLEPublish , " 12 . 13 . 14 . 15 " , & rr ) ) ; <nl> + } <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " deny " , " play " , " 12 . 13 . 14 . 15 " ) ; <nl> + HELPER_EXPECT_SUCCESS ( sec . do_check ( & rules , SrsRtmpConnPlay , " 11 . 12 . 13 . 14 " , & rr ) ) ; <nl> + } <nl> + <nl> + / / Allowed by rule . <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " allow " , " play " , " 12 . 13 . 14 . 15 " ) ; <nl> + HELPER_EXPECT_SUCCESS ( sec . do_check ( & rules , SrsRtmpConnPlay , " 12 . 13 . 14 . 15 " , & rr ) ) ; <nl> + } <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " allow " , " play " , " all " ) ; <nl> + HELPER_EXPECT_SUCCESS ( sec . do_check ( & rules , SrsRtmpConnPlay , " 12 . 13 . 14 . 15 " , & rr ) ) ; <nl> + } <nl> + <nl> + / / Allowed if not denied . <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " deny " , " play " , " 12 . 13 . 14 . 15 " ) ; <nl> + HELPER_EXPECT_SUCCESS ( sec . do_check ( & rules , SrsRtmpConnFMLEPublish , " 12 . 13 . 14 . 15 " , & rr ) ) ; <nl> + } <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " deny " , " play " , " all " ) ; <nl> + HELPER_EXPECT_SUCCESS ( sec . do_check ( & rules , SrsRtmpConnFMLEPublish , " 12 . 13 . 14 . 15 " , & rr ) ) ; <nl> + } <nl> + <nl> + / / Denied if not allowd . <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " allow " , " play " , " 11 . 12 . 13 . 14 " ) ; <nl> + HELPER_EXPECT_FAILED ( sec . do_check ( & rules , SrsRtmpConnFMLEPublish , " 12 . 13 . 14 . 15 " , & rr ) ) ; <nl> + } <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " allow " , " play " , " 11 . 12 . 13 . 14 " ) ; <nl> + HELPER_EXPECT_FAILED ( sec . do_check ( & rules , SrsRtmpConnPlay , " 12 . 13 . 14 . 15 " , & rr ) ) ; <nl> + } <nl> + <nl> + / / Denied if dup . <nl> + if ( true ) { <nl> + SrsSecurity sec ; SrsRequest rr ; SrsConfDirective rules ; <nl> + rules . get_or_create ( " allow " , " play " , " 11 . 12 . 13 . 14 " ) ; <nl> + rules . get_or_create ( " deny " , " play " , " 11 . 12 . 13 . 14 " ) ; <nl> + HELPER_EXPECT_FAILED ( sec . do_check ( & rules , SrsRtmpConnPlay , " 11 . 12 . 13 . 14 " , & rr ) ) ; <nl> + } <nl> + <nl> + / / SRS apply the following simple strategies one by one : <nl> + / / 1 . allow all if security disabled . <nl> + / / 2 . default to deny all when security enabled . <nl> + / / 3 . allow if matches allow strategy . <nl> + / / 4 . deny if matches deny strategy . <nl> + } <nl> + <nl>
For , refactor security check . 3 . 0 . 114
ossrs/srs
c51c378869747d40d4bd799be37decedc0c931f4
2020-02-04T11:07:54Z
mmm a / CMakeLists . txt <nl> ppp b / CMakeLists . txt <nl> set ( optional_deps Alsa <nl> CCache <nl> CEC <nl> ClangFormat <nl> + Dav1d <nl> DBus <nl> Iso9660pp <nl> LCMS2 <nl> mmm a / cmake / modules / FindDav1d . cmake <nl> ppp b / cmake / modules / FindDav1d . cmake <nl> if ( PKG_CONFIG_FOUND ) <nl> pkg_check_modules ( PC_DAV1D dav1d QUIET ) <nl> endif ( ) <nl> <nl> - find_library ( DAV1D_LIBRARY NAMES dav1d <nl> + find_library ( DAV1D_LIBRARY NAMES dav1d libdav1d <nl> PATHS $ { PC_DAV1D_LIBDIR } ) <nl> <nl> find_path ( DAV1D_INCLUDE_DIR NAMES dav1d / dav1d . h <nl> find_path ( DAV1D_INCLUDE_DIR NAMES dav1d / dav1d . h <nl> <nl> set ( DAV1D_VERSION $ { PC_DAV1D_VERSION } ) <nl> <nl> - if ( NOT DAV1D_LIBRARY AND NOT DAV1D_INCLUDE_DIR AND NOT DAV1D_VERSION ) <nl> - set ( ENABLE_INTERNAL_DAV1D ON ) <nl> - message ( STATUS " libdav1d not found , falling back to internal build " ) <nl> - endif ( ) <nl> - <nl> if ( ENABLE_INTERNAL_DAV1D ) <nl> include ( ExternalProject ) <nl> <nl> mmm a / cmake / modules / FindFFMPEG . cmake <nl> ppp b / cmake / modules / FindFFMPEG . cmake <nl> if ( NOT FFMPEG_FOUND ) <nl> message ( STATUS " FFMPEG_URL : $ { FFMPEG_URL } " ) <nl> endif ( ) <nl> <nl> - find_package ( Dav1d ) <nl> + if ( NOT DAV1D_FOUND ) <nl> + message ( STATUS " dav1d not found , internal ffmpeg build will be missing AV1 support ! " ) <nl> + endif ( ) <nl> <nl> set ( FFMPEG_OPTIONS - DENABLE_CCACHE = $ { ENABLE_CCACHE } <nl> - DCCACHE_PROGRAM = $ { CCACHE_PROGRAM } <nl> mmm a / project / BuildDependencies / scripts / 0_package . target - win10 - arm . list <nl> ppp b / project / BuildDependencies / scripts / 0_package . target - win10 - arm . list <nl> <nl> ; PLEASE KEEP THIS LIST IN ALPHABETICAL ORDER ! <nl> crossguid - 0 . 2 . 2 - win10 - arm - v141 - 20200105 . 7z <nl> curl - 7 . 67 . 0 - win10 - arm - v141 - 20200105 . 7z <nl> + dav1d - 0 . 6 . 0 - win10 - arm - v141 - 20200409 . 7z <nl> flatbuffers - 1 . 11 . 0 - 20200105 . 7z <nl> fmt - 6 . 1 . 2 - win10 - arm - v141 - 20200105 . 7z <nl> freetype - 2 . 10 . 1 - win10 - arm - v141 - 20200105 . 7z <nl> mmm a / project / BuildDependencies / scripts / 0_package . target - win10 - win32 . list <nl> ppp b / project / BuildDependencies / scripts / 0_package . target - win10 - win32 . list <nl> <nl> ; PLEASE KEEP THIS LIST IN ALPHABETICAL ORDER ! <nl> crossguid - 0 . 2 . 2 - win10 - win32 - v141 - 20200105 . 7z <nl> curl - 7 . 67 . 0 - win10 - win32 - v141 - 20200105 . 7z <nl> + dav1d - 0 . 6 . 0 - win10 - win32 - v141 - 20200409 . 7z <nl> flatbuffers - 1 . 11 . 0 - 20200105 . 7z <nl> fmt - 6 . 1 . 2 - win10 - win32 - v141 - 20200105 . 7z <nl> freetype - 2 . 10 . 1 - win10 - win32 - v141 - 20200105 . 7z <nl> mmm a / project / BuildDependencies / scripts / 0_package . target - win10 - x64 . list <nl> ppp b / project / BuildDependencies / scripts / 0_package . target - win10 - x64 . list <nl> <nl> ; PLEASE KEEP THIS LIST IN ALPHABETICAL ORDER ! <nl> crossguid - 0 . 2 . 2 - win10 - x64 - v141 - 20200105 . 7z <nl> curl - 7 . 67 . 0 - win10 - x64 - v141 - 20200105 . 7z <nl> + dav1d - 0 . 6 . 0 - win10 - x64 - v141 - 20200409 . 7z <nl> flatbuffers - 1 . 11 . 0 - 20200105 . 7z <nl> fmt - 6 . 1 . 2 - win10 - x64 - v141 - 20200105 . 7z <nl> freetype - 2 . 10 . 1 - win10 - x64 - v141 - 20200105 . 7z <nl> mmm a / project / BuildDependencies / scripts / 0_package . target - win32 . list <nl> ppp b / project / BuildDependencies / scripts / 0_package . target - win32 . list <nl> <nl> ; PLEASE KEEP THIS LIST IN ALPHABETICAL ORDER ! <nl> crossguid - 0 . 2 . 2 - win32 - v141 - 20200105 . 7z <nl> curl - 7 . 67 . 0 - win32 - v141 - 20200105 . 7z <nl> + dav1d - 0 . 6 . 0 - win32 - v141 - 20200409 . 7z <nl> detours - 64ec13 - win32 - v141 - 20200105 . 7z <nl> dnssd - 878 . 260 . 1 - win32 - v141 - 20200105 . 7z <nl> flatbuffers - 1 . 11 . 0 - 20200105 . 7z <nl> mmm a / project / BuildDependencies / scripts / 0_package . target - x64 . list <nl> ppp b / project / BuildDependencies / scripts / 0_package . target - x64 . list <nl> <nl> ; PLEASE KEEP THIS LIST IN ALPHABETICAL ORDER ! <nl> crossguid - 0 . 2 . 2 - x64 - v141 - 20200105 . 7z <nl> curl - 7 . 67 . 0 - x64 - v141 - 20200105 . 7z <nl> + dav1d - 0 . 6 . 0 - x64 - v141 - 20200409 . 7z <nl> detours - 64ec13 - x64 - v141 - 20200105 . 7z <nl> dnssd - 878 . 260 . 1 - x64 - v141 - 20200105 . 7z <nl> flatbuffers - 1 . 11 . 0 - 20200105 . 7z <nl> mmm a / tools / buildsteps / windows / ffmpeg_options . txt <nl> ppp b / tools / buildsteps / windows / ffmpeg_options . txt <nl> <nl> - - enable - runtime - cpudetect <nl> - - enable - static <nl> - - enable - zlib <nl> + - - enable - libdav1d <nl> new file mode 100644 <nl> index 000000000000 . . 716465ff0f81 <nl> mmm / dev / null <nl> ppp b / tools / buildsteps / windows / patches / 0005 - ffmpeg - detect - dav1d . patch <nl> <nl> pppmmm a / configure <nl> ppp + b / configure <nl> + enabled libcelt & & require libcelt celt / celt . h celt_decode - lcelt0 & & <nl> + die " ERROR : libcelt must be installed and version must be > = 0 . 11 . 0 . " ; } <nl> + enabled libcaca & & require_pkg_config libcaca caca caca . h caca_create_canvas <nl> + enabled libcodec2 & & require libcodec2 codec2 / codec2 . h codec2_create - lcodec2 <nl> + - enabled libdav1d & & require_pkg_config libdav1d " dav1d > = 0 . 2 . 1 " " dav1d / dav1d . h " dav1d_version <nl> + + enabled libdav1d & & require libdav1d dav1d / dav1d . h dav1d_version - llibdav1d <nl> + enabled libdavs2 & & require_pkg_config libdavs2 " davs2 > = 1 . 6 . 0 " davs2 . h davs2_decoder_open <nl> + enabled libdc1394 & & require_pkg_config libdc1394 libdc1394 - 2 dc1394 / dc1394 . h dc1394_new <nl> + enabled libdrm & & require_pkg_config libdrm libdrm xf86drm . h drmGetVersion <nl>
Merge pull request from lrusak / dav1d - windows
xbmc/xbmc
8e4801e28a6a513780542062cd30c4173b27040f
2020-04-18T01:02:47Z
mmm a / test / test_jit_fuser_te . py <nl> ppp b / test / test_jit_fuser_te . py <nl> def data_for ( self , dtype , device = " cuda " , size = None ) : <nl> else : <nl> return v . to ( dtype ) <nl> <nl> - @ unittest . skipIf ( not LLVM_ENABLED , " TODO : bugs in ir eval " ) <nl> def test_unary_ops ( self ) : <nl> def apply ( fn ) : <nl> return lambda x : fn ( x ) <nl> mmm a / torch / csrc / jit / tensorexpr / kernel . cpp <nl> ppp b / torch / csrc / jit / tensorexpr / kernel . cpp <nl> ExprHandle TensorExprKernel : : constant ( const torch : : jit : : Value * v ) { <nl> return scalars_ . at ( v - > unique ( ) ) ; <nl> } <nl> <nl> - ExprHandle promoteIntegerToFloat ( const ExprHandle & e ) { <nl> + ExprHandle promoteIntegerToDefaultType ( const ExprHandle & e ) { <nl> auto scalarType = static_cast < c10 : : ScalarType > ( e . dtype ( ) . scalar_type ( ) ) ; <nl> if ( ! c10 : : isIntegralType ( scalarType , / * includeBool * / true ) ) { <nl> return e ; <nl> } <nl> - auto defaultType = static_cast < tensorexpr : : ScalarType > ( <nl> - c10 : : typeMetaToScalarType ( c10 : : get_default_dtype ( ) ) ) ; <nl> - return Cast : : make ( Dtype ( defaultType , e . dtype ( ) . lanes ( ) ) , e ) ; <nl> + <nl> + auto defaultType = c10 : : typeMetaToScalarType ( c10 : : get_default_dtype ( ) ) ; <nl> + <nl> + / / We intend to promote Integers to floating - point types <nl> + TORCH_INTERNAL_ASSERT ( <nl> + ! c10 : : isIntegralType ( defaultType , / * includeBool * / true ) ) ; <nl> + <nl> + return Cast : : make ( <nl> + Dtype ( <nl> + static_cast < tensorexpr : : ScalarType > ( defaultType ) , e . dtype ( ) . lanes ( ) ) , <nl> + e ) ; <nl> } <nl> <nl> - void TensorExprKernel : : promoteInputs ( std : : vector < ExprHandle > & inputs ) { <nl> + ExprHandle promoteHalfToFloat ( const ExprHandle & e ) { <nl> + auto scalarType = static_cast < c10 : : ScalarType > ( e . dtype ( ) . scalar_type ( ) ) ; <nl> + auto floatType = static_cast < c10 : : ScalarType > ( tensorexpr : : ScalarType : : Float ) ; <nl> + if ( c10 : : isFloatingType ( scalarType ) & & <nl> + ( c10 : : elementSize ( scalarType ) < c10 : : elementSize ( floatType ) ) ) { <nl> + return Cast : : make ( <nl> + Dtype ( tensorexpr : : ScalarType : : Float , e . dtype ( ) . lanes ( ) ) , e ) ; <nl> + } else { <nl> + return e ; <nl> + } <nl> + } <nl> + <nl> + ExprHandle promoteHalfToFloatAndIntegerToDefaultType ( const ExprHandle & e ) { <nl> + auto scalarType = static_cast < c10 : : ScalarType > ( e . dtype ( ) . scalar_type ( ) ) ; <nl> + if ( c10 : : isIntegralType ( scalarType , / * includeBool * / true ) ) { <nl> + return promoteIntegerToDefaultType ( e ) ; <nl> + } else { <nl> + return promoteHalfToFloat ( e ) ; <nl> + } <nl> + } <nl> + <nl> + bool TensorExprKernel : : checkTypes ( <nl> + const ScalarType highType , <nl> + const int typeConstraints ) { <nl> + if ( typeConstraints = = kAllTypes ) { <nl> + return true ; <nl> + } <nl> + <nl> + if ( is_integral ( highType ) ) { <nl> + return ( typeConstraints & kIntegralTypes ) ! = 0 ; <nl> + } else if ( is_floating_point ( highType ) ) { <nl> + return ( typeConstraints & kFloatingPointTypes ) ! = 0 ; <nl> + } else if ( highType = = ScalarType : : Bool ) { <nl> + return ( typeConstraints & kBoolType ) ! = 0 ; <nl> + } <nl> + <nl> + / / assume JIT not supporting complex and qint yet <nl> + TORCH_INTERNAL_ASSERT ( ( typeConstraints & ( kQintTypes | kComplexTypes ) ) = = 0 ) ; <nl> + return false ; <nl> + } <nl> + <nl> + void TensorExprKernel : : promoteInputs ( <nl> + std : : vector < ExprHandle > & inputs , <nl> + const int typeConstraints ) { <nl> if ( inputs . empty ( ) ) { <nl> return ; <nl> } <nl> void TensorExprKernel : : promoteInputs ( std : : vector < ExprHandle > & inputs ) { <nl> highType = promoteTypes ( highType , input . dtype ( ) . scalar_type ( ) ) ; <nl> } <nl> <nl> + if ( ! checkTypes ( highType , typeConstraints ) ) { <nl> + throw unsupported_dtype ( ) ; <nl> + } <nl> + <nl> for ( ExprHandle & e : inputs ) { <nl> e = promoteToDtype ( e , highType ) ; <nl> } <nl> std : : vector < ExprHandle > TensorExprKernel : : valueShape ( <nl> Tensor * TensorExprKernel : : computeOneOperand ( <nl> const std : : string & name , <nl> const torch : : jit : : Value * v , <nl> - const std : : function < ExprHandle ( const ExprHandle & ) > & innerExpr ) { <nl> + const std : : function < ExprHandle ( const ExprHandle & ) > & innerExpr , <nl> + const int checkParamTypes ) { <nl> auto const & n = v - > node ( ) ; <nl> auto const & shape = valueShape ( n - > inputs ( ) [ 0 ] ) ; <nl> return Compute ( <nl> name , <nl> c10 : : fmap < DimArg > ( shape ) , <nl> - [ this , v , innerExpr ] ( const std : : vector < VarHandle > & axes ) { <nl> + [ this , v , innerExpr , checkParamTypes ] ( <nl> + const std : : vector < VarHandle > & axes ) { <nl> auto const & n = v - > node ( ) ; <nl> std : : vector < ExprHandle > indices ( axes . begin ( ) , axes . end ( ) ) ; <nl> std : : vector < ExprHandle > inputs = { <nl> tensorOrConstant ( n - > inputs ( ) [ 0 ] , indices ) } ; <nl> - <nl> - promoteInputs ( inputs ) ; <nl> + promoteInputs ( inputs , checkParamTypes ) ; <nl> ExprHandle compute = innerExpr ( inputs [ 0 ] ) ; <nl> return demoteOutput ( compute , n - > output ( ) ) ; <nl> } ) ; <nl> Tensor * TensorExprKernel : : computeValue ( const torch : : jit : : Value * v ) { <nl> case aten : : div : { <nl> return computeTwoOperand ( <nl> " aten_div " , v , [ ] ( const ExprHandle & lhs , const ExprHandle & rhs ) { <nl> - return promoteIntegerToFloat ( lhs ) / promoteIntegerToFloat ( rhs ) ; <nl> + return promoteIntegerToDefaultType ( lhs ) / <nl> + promoteIntegerToDefaultType ( rhs ) ; <nl> } ) ; <nl> } break ; <nl> <nl> Tensor * TensorExprKernel : : computeValue ( const torch : : jit : : Value * v ) { <nl> <nl> case aten : : sigmoid : { <nl> return computeOneOperand ( " aten_sigmoid " , v , [ ] ( const ExprHandle & a ) { <nl> - return sigmoid ( promoteIntegerToFloat ( a ) ) ; <nl> + return sigmoid ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> Tensor * TensorExprKernel : : computeValue ( const torch : : jit : : Value * v ) { <nl> <nl> case aten : : log : { <nl> return computeOneOperand ( " aten_log " , v , [ ] ( const ExprHandle & a ) { <nl> - return log ( promoteIntegerToFloat ( a ) ) ; <nl> + return log ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : log10 : { <nl> return computeOneOperand ( " aten_log10 " , v , [ ] ( const ExprHandle & a ) { <nl> - return log10 ( promoteIntegerToFloat ( a ) ) ; <nl> + return log10 ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : log1p : { <nl> return computeOneOperand ( " aten_log1p " , v , [ ] ( const ExprHandle & a ) { <nl> - return log1p ( promoteIntegerToFloat ( a ) ) ; <nl> + return log1p ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : log2 : { <nl> return computeOneOperand ( " aten_log2 " , v , [ ] ( const ExprHandle & a ) { <nl> - return log2 ( promoteIntegerToFloat ( a ) ) ; <nl> + return log2 ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> Tensor * TensorExprKernel : : computeValue ( const torch : : jit : : Value * v ) { <nl> <nl> case aten : : expm1 : { <nl> return computeOneOperand ( " aten_expm1 " , v , [ ] ( const ExprHandle & a ) { <nl> - return expm1 ( promoteIntegerToFloat ( a ) ) ; <nl> + return expm1 ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : erf : { <nl> return computeOneOperand ( " aten_erf " , v , [ ] ( const ExprHandle & a ) { <nl> - return erf ( promoteIntegerToFloat ( a ) ) ; <nl> + return erf ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : erfc : { <nl> return computeOneOperand ( " aten_erfc " , v , [ ] ( const ExprHandle & a ) { <nl> - return erfc ( promoteIntegerToFloat ( a ) ) ; <nl> + return erfc ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : cos : { <nl> return computeOneOperand ( " aten_cos " , v , [ ] ( const ExprHandle & a ) { <nl> - return cos ( promoteIntegerToFloat ( a ) ) ; <nl> + return cos ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : sin : { <nl> return computeOneOperand ( " aten_sin " , v , [ ] ( const ExprHandle & a ) { <nl> - return sin ( promoteIntegerToFloat ( a ) ) ; <nl> + return sin ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : tan : { <nl> return computeOneOperand ( " aten_tan " , v , [ ] ( const ExprHandle & a ) { <nl> - return tan ( promoteIntegerToFloat ( a ) ) ; <nl> + return tan ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> Tensor * TensorExprKernel : : computeValue ( const torch : : jit : : Value * v ) { <nl> <nl> case aten : : acos : { <nl> return computeOneOperand ( " aten_acos " , v , [ ] ( const ExprHandle & a ) { <nl> - return acos ( promoteIntegerToFloat ( a ) ) ; <nl> + return acos ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : asin : { <nl> return computeOneOperand ( " aten_asin " , v , [ ] ( const ExprHandle & a ) { <nl> - return asin ( promoteIntegerToFloat ( a ) ) ; <nl> + return asin ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : cosh : { <nl> return computeOneOperand ( " aten_cosh " , v , [ ] ( const ExprHandle & a ) { <nl> - return cosh ( promoteIntegerToFloat ( a ) ) ; <nl> + return cosh ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : sinh : { <nl> return computeOneOperand ( " aten_sinh " , v , [ ] ( const ExprHandle & a ) { <nl> - return sinh ( promoteIntegerToFloat ( a ) ) ; <nl> + return sinh ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : atan : { <nl> return computeOneOperand ( " aten_atan " , v , [ ] ( const ExprHandle & a ) { <nl> - return atan ( promoteIntegerToFloat ( a ) ) ; <nl> + return atan ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> Tensor * TensorExprKernel : : computeValue ( const torch : : jit : : Value * v ) { <nl> return computeTwoOperand ( <nl> " aten_atan2 " , v , [ ] ( const ExprHandle & lhs , const ExprHandle & rhs ) { <nl> return atan2 ( <nl> - promoteIntegerToFloat ( lhs ) , promoteIntegerToFloat ( rhs ) ) ; <nl> + promoteIntegerToDefaultType ( lhs ) , <nl> + promoteIntegerToDefaultType ( rhs ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : tanh : { <nl> return computeOneOperand ( " aten_tanh " , v , [ ] ( const ExprHandle & a ) { <nl> - return tanh ( promoteIntegerToFloat ( a ) ) ; <nl> + return tanh ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> case aten : : sqrt : { <nl> return computeOneOperand ( " aten_sqrt " , v , [ ] ( const ExprHandle & a ) { <nl> - return sqrt ( promoteIntegerToFloat ( a ) ) ; <nl> + return tensorexpr : : sqrt ( promoteIntegerToDefaultType ( a ) ) ; <nl> } ) ; <nl> } break ; <nl> <nl> Tensor * TensorExprKernel : : computeValue ( const torch : : jit : : Value * v ) { <nl> <nl> case aten : : abs : { <nl> return computeOneOperand ( <nl> - " aten_abs " , v , [ ] ( const ExprHandle & a ) { return fabs ( a ) ; } ) ; <nl> + " aten_abs " , <nl> + v , <nl> + [ ] ( const ExprHandle & a ) { <nl> + return fabs ( promoteHalfToFloatAndIntegerToDefaultType ( a ) ) ; <nl> + } , <nl> + kIntegralTypes | kFloatingPointTypes | kBoolType ) ; <nl> } break ; <nl> <nl> case aten : : ceil : { <nl> Tensor * TensorExprKernel : : computeValue ( const torch : : jit : : Value * v ) { <nl> <nl> case aten : : frac : { <nl> return computeOneOperand ( <nl> - " aten_frac " , v , [ ] ( const ExprHandle & a ) { return a - floor ( a ) ; } ) ; <nl> + " aten_frac " , <nl> + v , <nl> + [ ] ( const ExprHandle & a ) { <nl> + auto aa = promoteHalfToFloat ( a ) ; <nl> + return aa - floor ( aa ) ; <nl> + } , <nl> + kFloatingPointTypes ) ; <nl> } break ; <nl> <nl> case aten : : lgamma : { <nl> mmm a / torch / csrc / jit / tensorexpr / kernel . h <nl> ppp b / torch / csrc / jit / tensorexpr / kernel . h <nl> class TORCH_API TensorExprKernel { <nl> } <nl> <nl> private : <nl> + enum ElementType { <nl> + kAllTypes = 0 , <nl> + kIntegralTypes = 1 < < 0 , <nl> + kFloatingPointTypes = 1 < < 1 , <nl> + kBoolType = 1 < < 2 , <nl> + kComplexTypes = 1 < < 3 , <nl> + kQintTypes = 1 < < 4 , <nl> + kNonComplexOrQintTypes = kIntegralTypes | kBoolType | kFloatingPointTypes , <nl> + } ; <nl> + <nl> enum BackendType { <nl> kUninitialized , <nl> kSimpleIREval , <nl> class TORCH_API TensorExprKernel { <nl> <nl> std : : vector < ExprHandle > valueShape ( const torch : : jit : : Value * v ) ; <nl> <nl> - void promoteInputs ( std : : vector < ExprHandle > & inputs ) ; <nl> + bool checkTypes ( const ScalarType highType , const int typeConstraints ) ; <nl> + <nl> + void promoteInputs ( <nl> + std : : vector < ExprHandle > & inputs , <nl> + int typeConstraints = kAllTypes ) ; <nl> <nl> ExprHandle demoteOutput ( const ExprHandle & e , const torch : : jit : : Value * v ) ; <nl> <nl> class TORCH_API TensorExprKernel { <nl> Tensor * computeOneOperand ( <nl> const std : : string & name , <nl> const torch : : jit : : Value * v , <nl> - const std : : function < ExprHandle ( const ExprHandle & ) > & innerExpr ) ; <nl> + const std : : function < ExprHandle ( const ExprHandle & ) > & innerExpr , <nl> + const int checkParamTypes = kAllTypes ) ; <nl> <nl> Tensor * computeTwoOperand ( <nl> const std : : string & name , <nl>
[ NNC ] Add missing data type support for abs and frac ( )
pytorch/pytorch
a47a087a4325696ddec345f2d631812329a69f0d
2020-12-11T01:47:15Z
mmm a / src / GUI . cpp <nl> ppp b / src / GUI . cpp <nl> void GUI : : updateDlList ( bool force ) { <nl> DLListModel - > setData ( DLListModel - > index ( row , UPSPEED ) , QVariant ( ( double ) torrentStatus . upload_payload_rate ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , STATUS ) , QVariant ( tr ( " Finished " ) ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , DLSPEED ) , QVariant ( ( double ) 0 . ) ) ; <nl> - DLListModel - > setData ( DLListModel - > index ( row , SEEDSLEECH ) , QVariant ( QString ( misc : : toString ( torrentStatus . num_complete , true ) . c_str ( ) ) + " / " + QString ( misc : : toString ( torrentStatus . num_incomplete , true ) . c_str ( ) ) ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , ETA ) , QVariant ( ( qlonglong ) - 1 ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , NAME ) , QVariant ( QIcon ( " : / Icons / skin / seeding . png " ) ) , Qt : : DecorationRole ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , PROGRESS ) , QVariant ( ( double ) 1 . ) ) ; <nl> void GUI : : updateDlList ( bool force ) { <nl> DLListModel - > setData ( DLListModel - > index ( row , STATUS ) , QVariant ( tr ( " Checking . . . " ) ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , NAME ) , QVariant ( QIcon ( " : / Icons / skin / connecting . png " ) ) , Qt : : DecorationRole ) ; <nl> setRowColor ( row , " grey " ) ; <nl> - DLListModel - > setData ( DLListModel - > index ( row , SEEDSLEECH ) , QVariant ( QString ( misc : : toString ( torrentStatus . num_complete , true ) . c_str ( ) ) + " / " + QString ( misc : : toString ( torrentStatus . num_incomplete , true ) . c_str ( ) ) ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , PROGRESS ) , QVariant ( ( double ) torrentStatus . progress ) ) ; <nl> break ; <nl> case torrent_status : : connecting_to_tracker : <nl> void GUI : : updateDlList ( bool force ) { <nl> DLListModel - > setData ( DLListModel - > index ( row , NAME ) , QVariant ( QIcon ( " : / Icons / skin / connecting . png " ) ) , Qt : : DecorationRole ) ; <nl> setRowColor ( row , " grey " ) ; <nl> } <nl> - DLListModel - > setData ( DLListModel - > index ( row , SEEDSLEECH ) , QVariant ( QString ( misc : : toString ( torrentStatus . num_complete , true ) . c_str ( ) ) + " / " + QString ( misc : : toString ( torrentStatus . num_incomplete , true ) . c_str ( ) ) ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , PROGRESS ) , QVariant ( ( double ) torrentStatus . progress ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , DLSPEED ) , QVariant ( ( double ) torrentStatus . download_payload_rate ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , UPSPEED ) , QVariant ( ( double ) torrentStatus . upload_payload_rate ) ) ; <nl> void GUI : : updateDlList ( bool force ) { <nl> DLListModel - > setData ( DLListModel - > index ( row , ETA ) , QVariant ( ( qlonglong ) - 1 ) ) ; <nl> setRowColor ( row , " black " ) ; <nl> } <nl> - DLListModel - > setData ( DLListModel - > index ( row , SEEDSLEECH ) , QVariant ( QString ( misc : : toString ( torrentStatus . num_complete , true ) . c_str ( ) ) + " / " + QString ( misc : : toString ( torrentStatus . num_incomplete , true ) . c_str ( ) ) ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , PROGRESS ) , QVariant ( ( double ) torrentStatus . progress ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , DLSPEED ) , QVariant ( ( double ) torrentStatus . download_payload_rate ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , UPSPEED ) , QVariant ( ( double ) torrentStatus . upload_payload_rate ) ) ; <nl> void GUI : : updateDlList ( bool force ) { <nl> DLListModel - > setData ( DLListModel - > index ( row , SEEDSLEECH ) , QVariant ( QString ( misc : : toString ( torrentStatus . num_complete , true ) . c_str ( ) ) + " / " + QString ( misc : : toString ( torrentStatus . num_incomplete , true ) . c_str ( ) ) ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , ETA ) , QVariant ( ( qlonglong ) - 1 ) ) ; <nl> } <nl> + if ( torrentStatus . num_complete = = - 1 & & torrentStatus . num_incomplete = = - 1 ) { <nl> + DLListModel - > setData ( DLListModel - > index ( row , SEEDSLEECH ) , QVariant ( tr ( " Unknown " ) ) ) ; <nl> + } else { <nl> + DLListModel - > setData ( DLListModel - > index ( row , SEEDSLEECH ) , QVariant ( QString ( misc : : toString ( torrentStatus . num_complete , true ) . c_str ( ) ) + " / " + QString ( misc : : toString ( torrentStatus . num_incomplete , true ) . c_str ( ) ) ) ) ; <nl> + } <nl> } <nl> } catch ( invalid_handle e ) { <nl> continue ; <nl> void GUI : : addTorrent ( const QString & path , bool fromScanDir , const QString & from_ <nl> DLListModel - > setData ( DLListModel - > index ( row , SIZE ) , QVariant ( ( qlonglong ) t . total_size ( ) ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , DLSPEED ) , QVariant ( ( double ) 0 . ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , UPSPEED ) , QVariant ( ( double ) 0 . ) ) ; <nl> - DLListModel - > setData ( DLListModel - > index ( row , SEEDSLEECH ) , QVariant ( " 0 / 0 " ) ) ; <nl> + DLListModel - > setData ( DLListModel - > index ( row , SEEDSLEECH ) , QVariant ( tr ( " Unknown " ) ) ) ; <nl> DLListModel - > setData ( DLListModel - > index ( row , ETA ) , QVariant ( ( qlonglong ) - 1 ) ) ; <nl> / / Pause torrent if it was paused last time <nl> if ( QFile : : exists ( misc : : qBittorrentPath ( ) + " BT_backup " + QDir : : separator ( ) + QString ( t . name ( ) . c_str ( ) ) + " . paused " ) ) { <nl>
- Display " Unknown " instead of " 0 / 0 " in SEEDS / LEECHS column when the tracker doesn ' t send this info
qbittorrent/qBittorrent
be73c482d0d5ae6cab79a72d092291b3772b66de
2006-12-27T14:43:57Z
mmm a / BUILD . gn <nl> ppp b / BUILD . gn <nl> source_set ( " electron_lib " ) { <nl> } <nl> <nl> sources + = get_target_outputs ( " : electron_fuses " ) <nl> + <nl> + if ( is_win & & enable_win_dark_mode_window_ui ) { <nl> + sources + = [ <nl> + " shell / browser / win / dark_mode . cc " , <nl> + " shell / browser / win / dark_mode . h " , <nl> + ] <nl> + libs + = [ " uxtheme . lib " ] <nl> + } <nl> } <nl> <nl> electron_paks ( " packed_resources " ) { <nl> mmm a / buildflags / BUILD . gn <nl> ppp b / buildflags / BUILD . gn <nl> buildflag_header ( " buildflags " ) { <nl> " ENABLE_ELECTRON_EXTENSIONS = $ enable_electron_extensions " , <nl> " ENABLE_BUILTIN_SPELLCHECKER = $ enable_builtin_spellchecker " , <nl> " ENABLE_PICTURE_IN_PICTURE = $ enable_picture_in_picture " , <nl> + " ENABLE_WIN_DARK_MODE_WINDOW_UI = $ enable_win_dark_mode_window_ui " , <nl> " OVERRIDE_LOCATION_PROVIDER = $ enable_fake_location_provider " , <nl> ] <nl> } <nl> mmm a / buildflags / buildflags . gni <nl> ppp b / buildflags / buildflags . gni <nl> declare_args ( ) { <nl> <nl> # Enable Spellchecker support <nl> enable_builtin_spellchecker = true <nl> + <nl> + # Undocumented Windows dark mode API <nl> + enable_win_dark_mode_window_ui = false <nl> } <nl> mmm a / shell / browser / ui / win / electron_desktop_window_tree_host_win . cc <nl> ppp b / shell / browser / ui / win / electron_desktop_window_tree_host_win . cc <nl> <nl> # include " shell / browser / ui / win / electron_desktop_window_tree_host_win . h " <nl> <nl> # include " base / win / windows_version . h " <nl> + # include " electron / buildflags / buildflags . h " <nl> # include " shell / browser / ui / views / win_frame_view . h " <nl> + # include " ui / base / win / hwnd_metrics . h " <nl> # include " ui / base / win / shell . h " <nl> <nl> + # if BUILDFLAG ( ENABLE_WIN_DARK_MODE_WINDOW_UI ) <nl> + # include " shell / browser / win / dark_mode . h " <nl> + # endif <nl> + <nl> namespace electron { <nl> <nl> ElectronDesktopWindowTreeHostWin : : ElectronDesktopWindowTreeHostWin ( <nl> bool ElectronDesktopWindowTreeHostWin : : PreHandleMSG ( UINT message , <nl> WPARAM w_param , <nl> LPARAM l_param , <nl> LRESULT * result ) { <nl> + # if BUILDFLAG ( ENABLE_WIN_DARK_MODE_WINDOW_UI ) <nl> + if ( message = = WM_NCCREATE ) { <nl> + HWND const hwnd = GetAcceleratedWidget ( ) ; <nl> + auto const theme_source = <nl> + ui : : NativeTheme : : GetInstanceForNativeUi ( ) - > theme_source ( ) ; <nl> + win : : SetDarkModeForWindow ( hwnd , theme_source ) ; <nl> + } <nl> + # endif <nl> + <nl> return native_window_view_ - > PreHandleMSG ( message , w_param , l_param , result ) ; <nl> } <nl> <nl> new file mode 100644 <nl> index 000000000000 . . c85bf18786c2 <nl> mmm / dev / null <nl> ppp b / shell / browser / win / dark_mode . cc <nl> <nl> + / / Copyright ( c ) 2020 Microsoft Inc . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE - CHROMIUM file . <nl> + <nl> + # include " shell / browser / win / dark_mode . h " <nl> + <nl> + # include < dwmapi . h > / / DwmSetWindowAttribute ( ) <nl> + <nl> + # include " base / files / file_path . h " <nl> + # include " base / scoped_native_library . h " <nl> + # include " base / win / pe_image . h " <nl> + # include " base / win / win_util . h " <nl> + # include " base / win / windows_version . h " <nl> + <nl> + / / This namespace contains code originally from <nl> + / / https : / / github . com / ysc3839 / win32 - darkmode / <nl> + / / governed by the MIT license and ( c ) Richard Yu <nl> + namespace { <nl> + <nl> + / / 1903 18362 <nl> + enum PreferredAppMode { Default , AllowDark , ForceDark , ForceLight , Max } ; <nl> + <nl> + bool g_darkModeSupported = false ; <nl> + bool g_darkModeEnabled = false ; <nl> + DWORD g_buildNumber = 0 ; <nl> + <nl> + enum WINDOWCOMPOSITIONATTRIB { <nl> + WCA_USEDARKMODECOLORS = 26 / / build 18875 + <nl> + } ; <nl> + struct WINDOWCOMPOSITIONATTRIBDATA { <nl> + WINDOWCOMPOSITIONATTRIB Attrib ; <nl> + PVOID pvData ; <nl> + SIZE_T cbData ; <nl> + } ; <nl> + <nl> + using fnSetWindowCompositionAttribute = <nl> + BOOL ( WINAPI * ) ( HWND hWnd , WINDOWCOMPOSITIONATTRIBDATA * ) ; <nl> + fnSetWindowCompositionAttribute _SetWindowCompositionAttribute = nullptr ; <nl> + <nl> + bool IsHighContrast ( ) { <nl> + HIGHCONTRASTW highContrast = { sizeof ( highContrast ) } ; <nl> + if ( SystemParametersInfoW ( SPI_GETHIGHCONTRAST , sizeof ( highContrast ) , <nl> + & highContrast , FALSE ) ) <nl> + return highContrast . dwFlags & HCF_HIGHCONTRASTON ; <nl> + return false ; <nl> + } <nl> + <nl> + void RefreshTitleBarThemeColor ( HWND hWnd , bool dark ) { <nl> + LONG ldark = dark ; <nl> + if ( g_buildNumber > = 20161 ) { <nl> + / / DWMA_USE_IMMERSIVE_DARK_MODE = 20 <nl> + DwmSetWindowAttribute ( hWnd , 20 , & ldark , sizeof dark ) ; <nl> + return ; <nl> + } <nl> + if ( g_buildNumber > = 18363 ) { <nl> + auto data = WINDOWCOMPOSITIONATTRIBDATA { WCA_USEDARKMODECOLORS , & ldark , <nl> + sizeof ldark } ; <nl> + _SetWindowCompositionAttribute ( hWnd , & data ) ; <nl> + return ; <nl> + } <nl> + DwmSetWindowAttribute ( hWnd , 0x13 , & ldark , sizeof ldark ) ; <nl> + } <nl> + <nl> + void InitDarkMode ( ) { <nl> + / / confirm that we ' re running on a version of Windows <nl> + / / where the Dark Mode API is known <nl> + auto * os_info = base : : win : : OSInfo : : GetInstance ( ) ; <nl> + g_buildNumber = os_info - > version_number ( ) . build ; <nl> + auto const version = os_info - > version ( ) ; <nl> + if ( ( version < base : : win : : Version : : WIN10_RS5 ) | | <nl> + ( version > base : : win : : Version : : WIN10_20H1 ) ) { <nl> + return ; <nl> + } <nl> + <nl> + / / load " SetWindowCompositionAttribute " , used in RefreshTitleBarThemeColor ( ) <nl> + _SetWindowCompositionAttribute = <nl> + reinterpret_cast < decltype ( _SetWindowCompositionAttribute ) > ( <nl> + base : : win : : GetUser32FunctionPointer ( " SetWindowCompositionAttribute " ) ) ; <nl> + if ( _SetWindowCompositionAttribute = = nullptr ) { <nl> + return ; <nl> + } <nl> + <nl> + / / load the dark mode functions from uxtheme . dll <nl> + / / * RefreshImmersiveColorPolicyState ( ) <nl> + / / * ShouldAppsUseDarkMode ( ) <nl> + / / * AllowDarkModeForApp ( ) <nl> + / / * SetPreferredAppMode ( ) <nl> + / / * AllowDarkModeForApp ( ) ( build < 18362 ) <nl> + / / * SetPreferredAppMode ( ) ( build > = 18362 ) <nl> + <nl> + base : : NativeLibrary uxtheme = <nl> + base : : PinSystemLibrary ( FILE_PATH_LITERAL ( " uxtheme . dll " ) ) ; <nl> + if ( ! uxtheme ) { <nl> + return ; <nl> + } <nl> + auto ux_pei = base : : win : : PEImage ( uxtheme ) ; <nl> + auto get_ux_proc_from_ordinal = [ & ux_pei ] ( int ordinal , auto * setme ) { <nl> + FARPROC proc = ux_pei . GetProcAddress ( reinterpret_cast < LPCSTR > ( ordinal ) ) ; <nl> + * setme = reinterpret_cast < decltype ( * setme ) > ( proc ) ; <nl> + } ; <nl> + <nl> + / / ordinal 104 <nl> + using fnRefreshImmersiveColorPolicyState = VOID ( WINAPI * ) ( ) ; <nl> + fnRefreshImmersiveColorPolicyState _RefreshImmersiveColorPolicyState = { } ; <nl> + get_ux_proc_from_ordinal ( 104 , & _RefreshImmersiveColorPolicyState ) ; <nl> + <nl> + / / ordinal 132 <nl> + using fnShouldAppsUseDarkMode = BOOL ( WINAPI * ) ( ) ; <nl> + fnShouldAppsUseDarkMode _ShouldAppsUseDarkMode = { } ; <nl> + get_ux_proc_from_ordinal ( 132 , & _ShouldAppsUseDarkMode ) ; <nl> + <nl> + / / ordinal 135 , in 1809 <nl> + using fnAllowDarkModeForApp = BOOL ( WINAPI * ) ( BOOL allow ) ; <nl> + fnAllowDarkModeForApp _AllowDarkModeForApp = { } ; <nl> + <nl> + / / ordinal 135 , in 1903 <nl> + typedef PreferredAppMode ( WINAPI * <nl> + fnSetPreferredAppMode ) ( PreferredAppMode appMode ) ; <nl> + fnSetPreferredAppMode _SetPreferredAppMode = { } ; <nl> + <nl> + if ( g_buildNumber < 18362 ) { <nl> + get_ux_proc_from_ordinal ( 135 , & _AllowDarkModeForApp ) ; <nl> + } else { <nl> + get_ux_proc_from_ordinal ( 135 , & _SetPreferredAppMode ) ; <nl> + } <nl> + <nl> + / / dark mode is supported iff we found the functions <nl> + g_darkModeSupported = _RefreshImmersiveColorPolicyState & & <nl> + _ShouldAppsUseDarkMode & & <nl> + ( _AllowDarkModeForApp | | _SetPreferredAppMode ) ; <nl> + if ( ! g_darkModeSupported ) { <nl> + return ; <nl> + } <nl> + <nl> + / / initial setup : allow dark mode to be used <nl> + if ( _AllowDarkModeForApp ) { <nl> + _AllowDarkModeForApp ( true ) ; <nl> + } else if ( _SetPreferredAppMode ) { <nl> + _SetPreferredAppMode ( AllowDark ) ; <nl> + } <nl> + _RefreshImmersiveColorPolicyState ( ) ; <nl> + <nl> + / / check to see if dark mode is currently enabled <nl> + g_darkModeEnabled = _ShouldAppsUseDarkMode ( ) & & ! IsHighContrast ( ) ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> + namespace electron { <nl> + <nl> + void EnsureInitialized ( ) { <nl> + static bool initialized = false ; <nl> + if ( ! initialized ) { <nl> + initialized = true ; <nl> + : : InitDarkMode ( ) ; <nl> + } <nl> + } <nl> + <nl> + bool IsDarkPreferred ( ui : : NativeTheme : : ThemeSource theme_source ) { <nl> + switch ( theme_source ) { <nl> + case ui : : NativeTheme : : ThemeSource : : kForcedLight : <nl> + return false ; <nl> + case ui : : NativeTheme : : ThemeSource : : kForcedDark : <nl> + return g_darkModeSupported ; <nl> + case ui : : NativeTheme : : ThemeSource : : kSystem : <nl> + return g_darkModeEnabled ; <nl> + } <nl> + } <nl> + <nl> + namespace win { <nl> + <nl> + void SetDarkModeForWindow ( HWND hWnd , <nl> + ui : : NativeTheme : : ThemeSource theme_source ) { <nl> + EnsureInitialized ( ) ; <nl> + RefreshTitleBarThemeColor ( hWnd , IsDarkPreferred ( theme_source ) ) ; <nl> + } <nl> + <nl> + } / / namespace win <nl> + <nl> + } / / namespace electron <nl> new file mode 100644 <nl> index 000000000000 . . 9e83d54ed7e7 <nl> mmm / dev / null <nl> ppp b / shell / browser / win / dark_mode . h <nl> <nl> + / / Copyright ( c ) 2020 Microsoft Inc . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE - CHROMIUM file . <nl> + <nl> + # ifndef SHELL_BROWSER_WIN_DARK_MODE_H_ <nl> + # define SHELL_BROWSER_WIN_DARK_MODE_H_ <nl> + <nl> + # ifdef WIN32_LEAN_AND_MEAN <nl> + # include < Windows . h > <nl> + # else <nl> + # define WIN32_LEAN_AND_MEAN <nl> + # include < Windows . h > <nl> + # undef WIN32_LEAN_AND_MEAN <nl> + # endif <nl> + <nl> + # include " ui / native_theme / native_theme . h " <nl> + <nl> + namespace electron { <nl> + <nl> + namespace win { <nl> + <nl> + void SetDarkModeForWindow ( HWND hWnd , ui : : NativeTheme : : ThemeSource theme_source ) ; <nl> + <nl> + } / / namespace win <nl> + <nl> + } / / namespace electron <nl> + <nl> + # endif / / SHELL_BROWSER_WIN_DARK_MODE_H_ <nl> mmm a / shell / common / api / features . cc <nl> ppp b / shell / common / api / features . cc <nl> bool IsPictureInPictureEnabled ( ) { <nl> return BUILDFLAG ( ENABLE_PICTURE_IN_PICTURE ) ; <nl> } <nl> <nl> + bool IsWinDarkModeWindowUiEnabled ( ) { <nl> + return BUILDFLAG ( ENABLE_WIN_DARK_MODE_WINDOW_UI ) ; <nl> + } <nl> + <nl> bool IsComponentBuild ( ) { <nl> # if defined ( COMPONENT_BUILD ) <nl> return true ; <nl> void Initialize ( v8 : : Local < v8 : : Object > exports , <nl> dict . SetMethod ( " isPictureInPictureEnabled " , & IsPictureInPictureEnabled ) ; <nl> dict . SetMethod ( " isComponentBuild " , & IsComponentBuild ) ; <nl> dict . SetMethod ( " isExtensionsEnabled " , & IsExtensionsEnabled ) ; <nl> + dict . SetMethod ( " isWinDarkModeWindowUiEnabled " , & IsWinDarkModeWindowUiEnabled ) ; <nl> } <nl> <nl> } / / namespace <nl> mmm a / typings / internal - ambient . d . ts <nl> ppp b / typings / internal - ambient . d . ts <nl> declare namespace NodeJS { <nl> isPictureInPictureEnabled ( ) : boolean ; <nl> isExtensionsEnabled ( ) : boolean ; <nl> isComponentBuild ( ) : boolean ; <nl> + isWinDarkModeWindowUiEnabled ( ) : boolean ; <nl> } <nl> <nl> interface IpcRendererBinding { <nl>
feat : honor ` nativeTheme . themeSource = ' dark ' ` before creating BrowserWindow on Windows ( )
electron/electron
f489e3054a44bf946ad56add94485ff74c845782
2020-10-28T20:00:21Z
mmm a / src / heap / heap . cc <nl> ppp b / src / heap / heap . cc <nl> class FixStaleLeftTrimmedHandlesVisitor : public RootVisitor { <nl> inline void FixHandle ( FullObjectSlot p ) { <nl> if ( ! ( * p ) . IsHeapObject ( ) ) return ; <nl> HeapObject current = HeapObject : : cast ( * p ) ; <nl> - const MapWord map_word = current . map_word ( ) ; <nl> - if ( ! map_word . IsForwardingAddress ( ) & & current . IsFreeSpaceOrFiller ( ) ) { <nl> + if ( ! current . map_word ( ) . IsForwardingAddress ( ) & & <nl> + current . IsFreeSpaceOrFiller ( ) ) { <nl> # ifdef DEBUG <nl> / / We need to find a FixedArrayBase map after walking the fillers . <nl> - while ( current . IsFreeSpaceOrFiller ( ) ) { <nl> + while ( ! current . map_word ( ) . IsForwardingAddress ( ) & & <nl> + current . IsFreeSpaceOrFiller ( ) ) { <nl> Address next = current . ptr ( ) ; <nl> if ( current . map ( ) = = ReadOnlyRoots ( heap_ ) . one_pointer_filler_map ( ) ) { <nl> next + = kTaggedSize ; <nl> class FixStaleLeftTrimmedHandlesVisitor : public RootVisitor { <nl> } <nl> current = HeapObject : : cast ( Object ( next ) ) ; <nl> } <nl> - DCHECK ( current . IsFixedArrayBase ( ) ) ; <nl> + DCHECK ( current . map_word ( ) . IsForwardingAddress ( ) | | <nl> + current . IsFixedArrayBase ( ) ) ; <nl> # endif / / DEBUG <nl> p . store ( Smi : : zero ( ) ) ; <nl> } <nl>
[ heap ] Fix DCHECK in FixStaleLeftTrimmedHandlesVisitor
v8/v8
4e0da20df2e73df81e921bde3931582620a1c7c4
2020-11-09T16:28:19Z
mmm a / folly / experimental / observer / WithJitter - inl . h <nl> ppp b / folly / experimental / observer / WithJitter - inl . h <nl> <nl> # include < stdexcept > <nl> # include < utility > <nl> <nl> + # include < fmt / chrono . h > <nl> # include < fmt / core . h > <nl> # include < glog / logging . h > <nl> <nl>
add missing include to fix build failure
facebook/folly
2a60d871d23df9dc3d875faf879e09a2c4ad971d
2020-10-05T22:08:39Z
mmm a / src / arch / linux / network . cc <nl> ppp b / src / arch / linux / network . cc <nl> linux_tcp_conn_t : : linux_tcp_conn_t ( const char * host , int port ) <nl> throw connect_failed_exc_t ( ) ; <nl> } <nl> <nl> + int non_blocking_res ; <nl> + non_blocking_res = fcntl ( sock , F_SETFL , O_NONBLOCK ) ; <nl> + guarantee_err ( non_blocking_res = = 0 , " Could not make socket non - blocking " ) ; <nl> + <nl> freeaddrinfo ( res ) ; <nl> } <nl> <nl> mmm a / src / btree / key_value_store . cc <nl> ppp b / src / btree / key_value_store . cc <nl> void btree_key_value_store_t : : finished_a_query ( ) { <nl> <nl> / * Process of shutting down * / <nl> <nl> - bool btree_key_value_store_t : : shutdown ( shutdown_callback_t * cb ) { <nl> + bool btree_key_value_store_t : : shutdown ( store_t : : shutdown_callback_t * cb ) { <nl> rassert ( state = = state_ready ) ; <nl> assert_thread ( ) ; <nl> state = state_shutting_down ; <nl> mmm a / src / btree / key_value_store . hpp <nl> ppp b / src / btree / key_value_store . hpp <nl> class btree_key_value_store_t : <nl> bool start_new ( ready_callback_t * cb , btree_key_value_store_static_config_t * static_config ) ; <nl> bool start_existing ( ready_callback_t * cb ) ; <nl> <nl> - struct shutdown_callback_t { <nl> - virtual void on_store_shutdown ( ) = 0 ; <nl> - virtual ~ shutdown_callback_t ( ) { } <nl> - } ; <nl> - bool shutdown ( shutdown_callback_t * cb ) ; <nl> + bool shutdown ( store_t : : shutdown_callback_t * cb ) ; <nl> <nl> public : <nl> / * store_t interface . * / <nl> class btree_key_value_store_t : <nl> <nl> / * Shutdown process * / <nl> <nl> - shutdown_callback_t * shutdown_callback ; <nl> + store_t : : shutdown_callback_t * shutdown_callback ; <nl> <nl> void shutdown_finish_queries ( ) ; / / Called on home thread <nl> bool shutdown_finish_queries_on_thread ( ) ; / / Called on each thread <nl> mmm a / src / conn_acceptor . cc <nl> ppp b / src / conn_acceptor . cc <nl> conn_acceptor_t : : ~ conn_acceptor_t ( ) { <nl> <nl> listener . reset ( ) ; / / Stop accepting any more new connections <nl> <nl> - pmap ( get_num_db_threads ( ) , & conn_acceptor_t : : close_connections , this ) ; <nl> + pmap ( get_num_db_threads ( ) - 1 , & conn_acceptor_t : : close_connections , this ) ; <nl> } <nl> <nl> void conn_acceptor_t : : close_connections ( int thread ) { <nl> mmm a / src / memcached / memcached . cc <nl> ppp b / src / memcached / memcached . cc <nl> void run_storage_command ( txt_memcached_handler_t * rh , storage_command_t sc , stor <nl> case store_t : : sr_data_provider_failed : <nl> rh - > writef ( " CLIENT_ERROR bad data chunk \ r \ n " ) ; <nl> break ; <nl> - / * case store_t : : sr_not_allowed : <nl> + case store_t : : sr_not_allowed : <nl> rh - > writef ( " CLIENT_ERROR writing not allowed on this store ( probably a slave ) \ r \ n " ) ; <nl> - break ; * / <nl> + break ; <nl> default : unreachable ( ) ; <nl> } <nl> } <nl> void run_storage_command ( txt_memcached_handler_t * rh , storage_command_t sc , stor <nl> case store_t : : apr_data_provider_failed : <nl> rh - > writef ( " CLIENT_ERROR bad data chunk \ r \ n " ) ; <nl> break ; <nl> - / * case apr_not_allowed : <nl> + case store_t : : apr_not_allowed : <nl> rh - > writef ( " CLIENT_ERROR writing not allowed on this store ( probably a slave ) \ r \ n " ) ; <nl> - break ; * / <nl> + break ; <nl> default : unreachable ( ) ; <nl> } <nl> } <nl> void run_incr_decr ( txt_memcached_handler_t * rh , store_key_and_buffer_t key , unsi <nl> case store_t : : incr_decr_result_t : : idr_not_numeric : <nl> rh - > writef ( " CLIENT_ERROR cannot increment or decrement non - numeric value \ r \ n " ) ; <nl> break ; <nl> - / * case incr_decr_result_t : : idr_not_allowed : <nl> + case store_t : : incr_decr_result_t : : idr_not_allowed : <nl> rh - > writef ( " CLIENT_ERROR writing not allowed on this store ( probably a slave ) \ r \ n " ) ; <nl> - break ; * / <nl> + break ; <nl> default : unreachable ( ) ; <nl> } <nl> } <nl> void run_delete ( txt_memcached_handler_t * rh , store_key_and_buffer_t key , bool no <nl> <nl> if ( ! noreply ) { <nl> switch ( res ) { <nl> - case store_t : : dr_deleted : rh - > writef ( " DELETED \ r \ n " ) ; break ; <nl> - case store_t : : dr_not_found : rh - > writef ( " NOT_FOUND \ r \ n " ) ; break ; <nl> + case store_t : : dr_deleted : <nl> + rh - > writef ( " DELETED \ r \ n " ) ; <nl> + break ; <nl> + case store_t : : dr_not_found : <nl> + rh - > writef ( " NOT_FOUND \ r \ n " ) ; <nl> + break ; <nl> + case store_t : : dr_not_allowed : <nl> + rh - > writef ( " CLIENT_ERROR writing not allowed on this store ( probably a slave ) \ r \ n " ) ; <nl> + break ; <nl> default : unreachable ( ) ; <nl> } <nl> } <nl> mmm a / src / replication / protocol . cc <nl> ppp b / src / replication / protocol . cc <nl> class protocol_exc_t : public std : : exception { <nl> / / 13 is the length of the text . <nl> const char STANDARD_HELLO_MAGIC [ 16 ] = " 13rethinkdbrepl " ; <nl> <nl> - bool valid_role ( uint32_t val ) { <nl> + bool message_parser_t : : valid_role ( uint32_t val ) { <nl> return val = = master | | val = = new_slave | | val = = slave ; <nl> } <nl> <nl> - void do_parse_hello_message ( tcp_conn_t * conn , message_callback_t * receiver ) { <nl> + void message_parser_t : : do_parse_hello_message ( tcp_conn_t * conn , message_callback_t * receiver ) { <nl> net_hello_t buf ; <nl> conn - > read ( & buf , sizeof ( buf ) ) ; <nl> <nl> void do_parse_hello_message ( tcp_conn_t * conn , message_callback_t * receiver ) { <nl> } <nl> <nl> template < class struct_type > <nl> - bool fits ( const char * buffer , size_t size ) { <nl> + bool message_parser_t : : fits ( const char * buffer , size_t size ) { <nl> return size > = sizeof ( struct_type ) ; <nl> } <nl> <nl> template < > <nl> - bool fits < net_small_set_t > ( const char * buffer , size_t size ) { <nl> + bool message_parser_t : : fits < net_small_set_t > ( const char * buffer , size_t size ) { <nl> const net_small_set_t * p = reinterpret_cast < const net_small_set_t * > ( buffer ) ; <nl> <nl> return sizeof ( net_small_set_t ) < size & & leaf_pair_fits ( p - > leaf_pair ( ) , size - sizeof ( net_small_set_t ) ) ; <nl> } <nl> <nl> template < > <nl> - bool fits < net_small_append_prepend_t > ( const char * buffer , size_t size ) { <nl> + bool message_parser_t : : fits < net_small_append_prepend_t > ( const char * buffer , size_t size ) { <nl> const net_small_append_prepend_t * p = reinterpret_cast < const net_small_append_prepend_t * > ( buffer ) ; <nl> <nl> return sizeof ( net_small_append_prepend_t ) < = size & & sizeof ( net_small_append_prepend_t ) + p - > size < = size ; <nl> } <nl> <nl> template < class struct_type > <nl> - ssize_t objsize ( const struct_type * buffer ) { <nl> + ssize_t message_parser_t : : objsize ( const struct_type * buffer ) { <nl> return sizeof ( struct_type ) ; <nl> } <nl> <nl> template < > <nl> - ssize_t objsize < net_small_set_t > ( const net_small_set_t * buffer ) { <nl> + ssize_t message_parser_t : : objsize < net_small_set_t > ( const net_small_set_t * buffer ) { <nl> return sizeof ( net_small_set_t ) + leaf : : pair_size ( buffer - > leaf_pair ( ) ) ; <nl> } <nl> <nl> template < > <nl> - ssize_t objsize < net_small_append_prepend_t > ( const net_small_append_prepend_t * buffer ) { <nl> + ssize_t message_parser_t : : objsize < net_small_append_prepend_t > ( const net_small_append_prepend_t * buffer ) { <nl> return sizeof ( net_small_append_prepend_t ) + buffer - > size ; <nl> } <nl> <nl> template < class message_type > <nl> - ssize_t try_parsing ( message_callback_t * receiver , const char * buffer , size_t size ) { <nl> + ssize_t message_parser_t : : try_parsing ( message_callback_t * receiver , const char * buffer , size_t size ) { <nl> typedef typename message_type : : net_struct_type net_struct_type ; <nl> if ( fits < net_struct_type > ( buffer , size ) ) { <nl> const net_struct_type * p = reinterpret_cast < const net_struct_type * > ( buffer ) ; <nl> ssize_t try_parsing ( message_callback_t * receiver , const char * buffer , size_t siz <nl> } <nl> <nl> template < class message_type > <nl> - bool parse_and_pop ( tcp_conn_t * conn , message_callback_t * receiver , const char * buffer , size_t size ) { <nl> + bool message_parser_t : : parse_and_pop ( tcp_conn_t * conn , message_callback_t * receiver , const char * buffer , size_t size ) { <nl> ssize_t sz = try_parsing < message_type > ( receiver , buffer , size ) ; <nl> if ( sz = = - 1 ) { <nl> return false ; <nl> bool parse_and_pop ( tcp_conn_t * conn , message_callback_t * receiver , const char * b <nl> } <nl> <nl> template < class message_type > <nl> - bool parse_and_stream ( tcp_conn_t * conn , message_callback_t * receiver , tcp_conn_t : : bufslice sl , std : : vector < value_stream_t * > & streams ) { <nl> + bool message_parser_t : : parse_and_stream ( tcp_conn_t * conn , message_callback_t * receiver , tcp_conn_t : : bufslice sl , std : : vector < value_stream_t * > & streams ) { <nl> typedef typename message_type : : first_struct_type first_struct_type ; <nl> / * if ( part_before_stream_fits < first_struct_type > ( sl ) ) { <nl> const first_struct_type * p = reinterpret_cast < const first_struct_type * > ( sl . buf ) ; <nl> bool parse_and_stream ( tcp_conn_t * conn , message_callback_t * receiver , tcp_conn_t <nl> return false ; <nl> } <nl> <nl> - void do_parse_normal_message ( tcp_conn_t * conn , message_callback_t * receiver , std : : vector < value_stream_t * > & streams ) { <nl> + void message_parser_t : : do_parse_normal_message ( tcp_conn_t * conn , message_callback_t * receiver , std : : vector < value_stream_t * > & streams ) { <nl> <nl> - for ( ; ; ) { <nl> + while ( keep_going ) { <nl> tcp_conn_t : : bufslice sl = conn - > peek ( ) ; <nl> if ( sl . len > = sizeof ( net_header_t ) ) { <nl> const char * buffer = reinterpret_cast < const char * > ( sl . buf ) ; <nl> void do_parse_normal_message ( tcp_conn_t * conn , message_callback_t * receiver , std <nl> } <nl> <nl> <nl> - void do_parse_messages ( tcp_conn_t * conn , message_callback_t * receiver ) { <nl> - do_parse_hello_message ( conn , receiver ) ; <nl> + void message_parser_t : : do_parse_messages ( tcp_conn_t * conn , message_callback_t * receiver ) { <nl> + try { <nl> + do_parse_hello_message ( conn , receiver ) ; <nl> <nl> - std : : vector < value_stream_t * > placeholder ; <nl> - for ( ; ; ) { <nl> + std : : vector < value_stream_t * > placeholder ; <nl> do_parse_normal_message ( conn , receiver , placeholder ) ; <nl> + } catch ( tcp_conn_t : : read_closed_exc_t & e ) { <nl> + if ( keep_going ) <nl> + receiver - > conn_closed ( ) ; <nl> } <nl> } <nl> <nl> - void parse_messages ( tcp_conn_t * conn , message_callback_t * receiver ) { <nl> - try { <nl> - do_parse_messages ( conn , receiver ) ; <nl> - } <nl> - catch ( tcp_conn_t : : read_closed_exc_t & e ) { <nl> - receiver - > conn_closed ( ) ; <nl> - } <nl> + void message_parser_t : : parse_messages ( tcp_conn_t * conn , message_callback_t * receiver ) { <nl> + keep_going = true ; <nl> + coro_t : : spawn ( & message_parser_t : : do_parse_messages , this , conn , receiver ) ; <nl> + } <nl> + <nl> + void message_parser_t : : stop_parsing ( ) { <nl> + keep_going = false ; <nl> } <nl> <nl> } / / namespace replication <nl> mmm a / src / replication / protocol . hpp <nl> ppp b / src / replication / protocol . hpp <nl> class message_callback_t { <nl> virtual void conn_closed ( ) = 0 ; <nl> } ; <nl> <nl> - void parse_messages ( tcp_conn_t * conn , message_callback_t * receiver ) ; <nl> + class message_parser_t { <nl> + public : <nl> + message_parser_t ( ) { } <nl> + ~ message_parser_t ( ) { } <nl> + <nl> + private : <nl> + bool keep_going ; / * used to signal the parser when to stop * / <nl> + <nl> + public : <nl> + void parse_messages ( tcp_conn_t * conn , message_callback_t * receiver ) ; <nl> + void stop_parsing ( ) ; <nl> + <nl> + private : <nl> + void do_parse_messages ( tcp_conn_t * conn , message_callback_t * receiver ) ; <nl> + void do_parse_normal_message ( tcp_conn_t * conn , message_callback_t * receiver , std : : vector < value_stream_t * > & streams ) ; <nl> <nl> + template < class message_type > <nl> + bool parse_and_stream ( tcp_conn_t * conn , message_callback_t * receiver , tcp_conn_t : : bufslice sl , std : : vector < value_stream_t * > & streams ) ; <nl> <nl> + template < class message_type > <nl> + bool parse_and_pop ( tcp_conn_t * conn , message_callback_t * receiver , const char * buffer , size_t size ) ; <nl> <nl> + template < class message_type > <nl> + ssize_t try_parsing ( message_callback_t * receiver , const char * buffer , size_t size ) ; <nl> <nl> + template < class struct_type > <nl> + ssize_t objsize ( const struct_type * buffer ) ; <nl> <nl> + template < class struct_type > <nl> + bool fits ( const char * buffer , size_t size ) ; <nl> <nl> + void do_parse_hello_message ( tcp_conn_t * conn , message_callback_t * receiver ) ; <nl> <nl> + bool valid_role ( uint32_t val ) ; <nl> + } ; <nl> } / / namespace replication <nl> <nl> <nl> mmm a / src / replication / slave . cc <nl> ppp b / src / replication / slave . cc <nl> slave_t : : slave_t ( store_t * internal_store , replication_config_t config ) <nl> : internal_store ( internal_store ) , config ( config ) , conn ( config . hostname , config . port ) , respond_to_queries ( false ) , n_retries ( RETRY_ATTEMPTS ) <nl> { <nl> failover . add_callback ( this ) ; <nl> - continue_on_thread ( home_thread , this ) ; <nl> + state = starting_up ; <nl> + continue_on_thread ( get_num_threads ( ) - 2 , this ) ; / / TODO make this work even if we ' re on the thread here ugh ugh ugh <nl> } <nl> <nl> slave_t : : ~ slave_t ( ) { } <nl> <nl> + bool slave_t : : shutdown ( shutdown_callback_t * cb ) { <nl> + parser . stop_parsing ( ) ; / / TODO put a callback on this <nl> + state = shut_down_parser ; <nl> + _cb = cb ; <nl> + continue_on_thread ( get_num_threads ( ) - 2 , this ) ; / / TODO make this work even if we ' re on the thread here ugh ugh ugh <nl> + <nl> + return false ; <nl> + } <nl> + <nl> store_t : : get_result_t slave_t : : get ( store_key_t * key ) <nl> { <nl> return internal_store - > get ( key ) ; <nl> store_t : : get_result_t slave_t : : get_cas ( store_key_t * key ) <nl> return internal_store - > get ( key ) ; <nl> } <nl> <nl> - store_t : : set_result_t slave_t : : set ( store_key_t * key , data_provider_t * data , mcflags_t flags , exptime_t exptime ) <nl> - { <nl> - return internal_store - > set ( key , data , flags , exptime ) ; <nl> + store_t : : set_result_t slave_t : : set ( store_key_t * key , data_provider_t * data , mcflags_t flags , exptime_t exptime ) { <nl> + if ( respond_to_queries ) <nl> + return internal_store - > set ( key , data , flags , exptime ) ; <nl> + else <nl> + return store_t : : sr_not_allowed ; <nl> } <nl> <nl> store_t : : set_result_t slave_t : : add ( store_key_t * key , data_provider_t * data , mcflags_t flags , exptime_t exptime ) <nl> store_t : : set_result_t slave_t : : add ( store_key_t * key , data_provider_t * data , mcfl <nl> <nl> store_t : : set_result_t slave_t : : replace ( store_key_t * key , data_provider_t * data , mcflags_t flags , exptime_t exptime ) <nl> { <nl> - return internal_store - > replace ( key , data , flags , exptime ) ; <nl> + if ( respond_to_queries ) <nl> + return internal_store - > replace ( key , data , flags , exptime ) ; <nl> + else <nl> + return store_t : : sr_not_allowed ; <nl> } <nl> <nl> store_t : : set_result_t slave_t : : cas ( store_key_t * key , data_provider_t * data , mcflags_t flags , exptime_t exptime , cas_t unique ) <nl> { <nl> - return internal_store - > cas ( key , data , flags , exptime , unique ) ; <nl> + if ( respond_to_queries ) <nl> + return internal_store - > cas ( key , data , flags , exptime , unique ) ; <nl> + else <nl> + return store_t : : sr_not_allowed ; <nl> } <nl> <nl> store_t : : incr_decr_result_t slave_t : : incr ( store_key_t * key , unsigned long long amount ) <nl> { <nl> - return internal_store - > incr ( key , amount ) ; <nl> + if ( respond_to_queries ) <nl> + return internal_store - > incr ( key , amount ) ; <nl> + else <nl> + return store_t : : incr_decr_result_t : : idr_not_allowed ; <nl> } <nl> <nl> store_t : : incr_decr_result_t slave_t : : decr ( store_key_t * key , unsigned long long amount ) <nl> { <nl> - return internal_store - > decr ( key , amount ) ; <nl> + if ( respond_to_queries ) <nl> + return internal_store - > decr ( key , amount ) ; <nl> + else <nl> + return store_t : : incr_decr_result_t : : idr_not_allowed ; <nl> } <nl> <nl> store_t : : append_prepend_result_t slave_t : : append ( store_key_t * key , data_provider_t * data ) <nl> { <nl> - return internal_store - > append ( key , data ) ; <nl> + if ( respond_to_queries ) <nl> + return internal_store - > append ( key , data ) ; <nl> + else <nl> + return store_t : : apr_not_allowed ; <nl> } <nl> <nl> store_t : : append_prepend_result_t slave_t : : prepend ( store_key_t * key , data_provider_t * data ) <nl> { <nl> - return internal_store - > prepend ( key , data ) ; <nl> + if ( respond_to_queries ) <nl> + return internal_store - > prepend ( key , data ) ; <nl> + else <nl> + return store_t : : apr_not_allowed ; <nl> } <nl> <nl> store_t : : delete_result_t slave_t : : delete_key ( store_key_t * key ) <nl> { <nl> - return internal_store - > delete_key ( key ) ; <nl> + if ( respond_to_queries ) <nl> + return internal_store - > delete_key ( key ) ; <nl> + else <nl> + return dr_not_allowed ; <nl> } <nl> <nl> void slave_t : : replicate ( replicant_t * cb , repli_timestamp cutoff ) <nl> void slave_t : : conn_closed ( ) <nl> conn = tcp_conn_t ( config . hostname , config . port ) ; <nl> logINF ( " Successfully reconnected to the server " ) ; <nl> success = true ; <nl> - parse_messages ( & conn , this ) ; <nl> + parser . parse_messages ( & conn , this ) ; <nl> } <nl> catch ( tcp_conn_t : : connect_failed_exc_t & e ) { <nl> logINF ( " Connection attempt : % d failed \ n " , reconnects_done ) ; <nl> void slave_t : : conn_closed ( ) <nl> if ( ! success ) failover . on_failure ( ) ; <nl> } <nl> <nl> + void slave_t : : on_thread_switch ( ) { <nl> + if ( state = = starting_up ) { <nl> + parser . parse_messages ( & conn , this ) ; <nl> + } else if ( state = = shut_down_parser ) { <nl> + if ( conn . is_read_open ( ) ) conn . shutdown_read ( ) ; <nl> + if ( conn . is_write_open ( ) ) conn . shutdown_write ( ) ; <nl> + state = shut_down_internal_store ; <nl> + continue_on_thread ( home_thread , this ) ; <nl> + } else if ( state = = shut_down_internal_store ) { <nl> + if ( internal_store - > shutdown ( _cb ) ) { <nl> + logINF ( " Store shutdown immediately " ) ; <nl> + _cb - > on_store_shutdown ( ) ; <nl> + } <nl> + } else { <nl> + unreachable ( ) ; <nl> + } <nl> + } <nl> + <nl> / * failover callback * / <nl> void slave_t : : on_failure ( ) { <nl> respond_to_queries = true ; <nl> mmm a / src / replication / slave . hpp <nl> ppp b / src / replication / slave . hpp <nl> struct slave_t : <nl> slave_t ( store_t * , replication_config_t ) ; <nl> ~ slave_t ( ) ; <nl> <nl> + bool shutdown ( store_t : : shutdown_callback_t * cb ) ; <nl> + private : <nl> + store_t : : shutdown_callback_t * _cb ; / / we ' ll need to store the cb at some point <nl> + <nl> private : <nl> store_t * internal_store ; <nl> replication_config_t config ; <nl> tcp_conn_t conn ; <nl> - <nl> + message_parser_t parser ; <nl> failover_t failover ; <nl> <nl> public : <nl> struct slave_t : <nl> bool respond_to_queries ; <nl> int n_retries ; <nl> <nl> + private : <nl> + enum { <nl> + starting_up = 0 , <nl> + shut_down_parser , <nl> + shut_down_internal_store , <nl> + shut_down <nl> + } state ; <nl> + <nl> public : <nl> - void on_thread_switch ( ) { <nl> - parse_messages ( & conn , this ) ; <nl> - } <nl> + void on_thread_switch ( ) ; <nl> } ; <nl> <nl> } / / namespace replication <nl> mmm a / src / server / server . cc <nl> ppp b / src / server / server . cc <nl> void server_main ( cmd_config_t * cmd_config , thread_pool_t * thread_pool ) { <nl> server_t server ( cmd_config , thread_pool ) ; <nl> <nl> { <nl> + / * Replication store * / <nl> + replication : : slave_t * slave_store = NULL ; <nl> + <nl> / * Start logger * / <nl> log_controller_t log_controller ; <nl> <nl> void server_main ( cmd_config_t * cmd_config , thread_pool_t * thread_pool ) { <nl> <nl> if ( cmd_config - > replication_config . active ) { <nl> logINF ( " Starting up as a slave . . . \ n " ) ; <nl> - replication : : slave_t slave_store ( & store , cmd_config - > replication_config ) ; <nl> - server . store = & slave_store ; <nl> + slave_store = new replication : : slave_t ( & store , cmd_config - > replication_config ) ; <nl> + server . store = slave_store ; <nl> } else { <nl> + logINF ( " Starting up as a free database . . . \ n " ) ; <nl> server . store = & store ; / * So things can access it * / <nl> } <nl> <nl> void server_main ( cmd_config_t * cmd_config , thread_pool_t * thread_pool ) { <nl> } <nl> <nl> / * Shut down key - value store * / <nl> - struct : public btree_key_value_store_t : : shutdown_callback_t , public cond_t { <nl> + struct : public store_t : : shutdown_callback_t , public cond_t { <nl> void on_store_shutdown ( ) { pulse ( ) ; } <nl> } store_shutdown_cb ; <nl> - if ( ! store . shutdown ( & store_shutdown_cb ) ) store_shutdown_cb . wait ( ) ; <nl> + if ( ! server . store - > shutdown ( & store_shutdown_cb ) ) store_shutdown_cb . wait ( ) ; <nl> + <nl> + if ( slave_store ) <nl> + delete slave_store ; <nl> } <nl> <nl> / * The penultimate step of shutting down is to make sure that all messages <nl> mmm a / src / store . hpp <nl> ppp b / src / store . hpp <nl> struct store_t { <nl> sr_too_large , <nl> / * Returned if the data_provider_t that you gave returned have_failed ( ) . * / <nl> sr_data_provider_failed , <nl> + / * Returned if the store doesn ' t want you to do what you ' re doing . * / <nl> + sr_not_allowed , <nl> } ; <nl> <nl> virtual set_result_t set ( store_key_t * key , data_provider_t * data , mcflags_t flags , exptime_t exptime ) = 0 ; <nl> struct store_t { <nl> enum result_t { <nl> idr_success , <nl> idr_not_found , <nl> - idr_not_numeric <nl> + idr_not_numeric , <nl> + idr_not_allowed , <nl> } res ; <nl> unsigned long long new_value ; / / Valid only if idr_success <nl> incr_decr_result_t ( ) { } <nl> struct store_t { <nl> apr_success , <nl> apr_too_large , <nl> apr_not_found , <nl> - apr_data_provider_failed <nl> + apr_data_provider_failed , <nl> + apr_not_allowed , <nl> } ; <nl> virtual append_prepend_result_t append ( store_key_t * key , data_provider_t * data ) = 0 ; <nl> virtual append_prepend_result_t prepend ( store_key_t * key , data_provider_t * data ) = 0 ; <nl> struct store_t { <nl> <nl> enum delete_result_t { <nl> dr_deleted , <nl> - dr_not_found <nl> + dr_not_found , <nl> + dr_not_allowed <nl> } ; <nl> <nl> virtual delete_result_t delete_key ( store_key_t * key ) = 0 ; <nl> struct store_t { <nl> virtual void replicate ( replicant_t * cb , repli_timestamp cutoff ) = 0 ; <nl> virtual void stop_replicating ( replicant_t * cb ) = 0 ; <nl> <nl> + public : <nl> + struct shutdown_callback_t { <nl> + virtual void on_store_shutdown ( ) = 0 ; <nl> + virtual ~ shutdown_callback_t ( ) { } <nl> + } ; <nl> + virtual bool shutdown ( shutdown_callback_t * cb ) = 0 ; <nl> + <nl> virtual ~ store_t ( ) { } <nl> } ; <nl> <nl>
Setup replication .
rethinkdb/rethinkdb
866259c9c1cb992ac52b2fe843040681ba8936dc
2011-01-22T01:45:10Z
mmm a / src / Storages / MergeTree / MergeTreeMutationStatus . h <nl> ppp b / src / Storages / MergeTree / MergeTreeMutationStatus . h <nl> <nl> # include < Core / Names . h > <nl> # include < optional > <nl> # include < map > <nl> + # include < ctime > <nl> <nl> <nl> namespace DB <nl>
Trying to fix FreeBSD build
ClickHouse/ClickHouse
978f28662534acddca19a222327854230b1e08ee
2020-07-23T08:00:18Z
new file mode 100644 <nl> index 00000000000 . . 4650d44c709 <nl> Binary files / dev / null and b / modules / calib3d / doc / pics / distortion_examples . png differ <nl> mmm a / modules / calib3d / include / opencv2 / calib3d . hpp <nl> ppp b / modules / calib3d / include / opencv2 / calib3d . hpp <nl> v = f_y * y ' ' + c_y <nl> tangential distortion coefficients . \ f $ s_1 \ f $ , \ f $ s_2 \ f $ , \ f $ s_3 \ f $ , and \ f $ s_4 \ f $ , are the thin prism distortion <nl> coefficients . Higher - order coefficients are not considered in OpenCV . <nl> <nl> + The next figure shows two common types of radial distortion : barrel distortion ( typically \ f $ k_1 > 0 \ f $ and pincushion distortion ( typically \ f $ k_1 < 0 \ f $ ) . <nl> + <nl> + ! [ ] ( pics / distortion_examples . png ) <nl> + <nl> In some cases the image sensor may be tilted in order to focus an oblique plane in front of the <nl> camera ( Scheimpfug condition ) . This can be useful for particle image velocimetry ( PIV ) or <nl> triangulation with a laser fan . The tilt causes a perspective distortion of \ f $ x ' ' \ f $ and <nl>
Add distortion example images for calib3d documentation .
opencv/opencv
ce7811e5dd044eee029366dd99b4fa4738ca8bc3
2016-10-09T18:35:58Z
mmm a / include / internal / catch_test_case_info . hpp <nl> ppp b / include / internal / catch_test_case_info . hpp <nl> namespace Catch { <nl> return TestCaseInfo : : None ; <nl> } <nl> inline bool isReservedTag ( std : : string const & tag ) { <nl> - return TestCaseInfo : : None & & tag . size ( ) > 0 & & ! isalnum ( tag [ 0 ] ) ; <nl> + return parseSpecialTag ( tag ) = = TestCaseInfo : : None & & tag . size ( ) > 0 & & ! isalnum ( tag [ 0 ] ) ; <nl> } <nl> inline void enforceNotReservedTag ( std : : string const & tag , SourceLineInfo const & _lineInfo ) { <nl> if ( isReservedTag ( tag ) ) { <nl>
Restored tag parsing when checking for reserved tags
catchorg/Catch2
0ae7578028fe30135015ace15a97009a547f2d46
2015-03-04T19:01:25Z
mmm a / lib / Sema / DerivedConformanceCaseIterable . cpp <nl> ppp b / lib / Sema / DerivedConformanceCaseIterable . cpp <nl> static bool canDeriveConformance ( NominalTypeDecl * type ) { <nl> void deriveCaseIterable_enum_getter ( AbstractFunctionDecl * funcDecl ) { <nl> auto * parentDC = funcDecl - > getDeclContext ( ) ; <nl> auto * parentEnum = parentDC - > getAsEnumOrEnumExtensionContext ( ) ; <nl> - auto enumTy = parentEnum - > getDeclaredTypeInContext ( ) ; <nl> + auto enumTy = parentDC - > getDeclaredTypeInContext ( ) ; <nl> auto & C = parentDC - > getASTContext ( ) ; <nl> <nl> SmallVector < Expr * , 8 > elExprs ; <nl> mmm a / test / Sema / enum_conformance_synthesis . swift <nl> ppp b / test / Sema / enum_conformance_synthesis . swift <nl> enum Instrument { <nl> <nl> extension Instrument : Equatable { } <nl> <nl> + extension Instrument : CaseIterable { } <nl> + <nl> + enum UnusedGeneric < T > { <nl> + case a , b , c <nl> + } <nl> + extension UnusedGeneric : CaseIterable { } <nl> + <nl> / / Explicit conformance should work too <nl> public enum Medicine { <nl> case Antibiotic <nl>
[ Sema ] Fix synthesis of CaseIterable conformances in extensions of generic types .
apple/swift
041287f0ba39a52235cac1310647caf68378eece
2018-05-06T23:41:26Z
mmm a / tensorflow / contrib / cudnn_rnn / python / ops / cudnn_rnn_ops . py <nl> ppp b / tensorflow / contrib / cudnn_rnn / python / ops / cudnn_rnn_ops . py <nl> def __init__ ( self , <nl> for param , param_name in zip ( params , param_names ) <nl> ] <nl> super ( RNNParamsSaveable , self ) . __init__ ( <nl> - param_variables [ 0 ] , specs , name ) <nl> + array_ops . identity ( param_variables [ 0 ] ) , specs , name ) <nl> <nl> def restore ( self , restored_tensors , restored_shapes ) : <nl> if ( self . _cudnn_rnn . direction = = CUDNN_RNN_UNIDIRECTION and <nl>
Use identity of param variable in cudnn_rnn . RNNParamsSaveable instead of parameter
tensorflow/tensorflow
446450369b9f4375cf26c1c1bc3b9a3fd93059f5
2017-07-28T05:20:09Z
mmm a / DEPS <nl> ppp b / DEPS <nl> vars = { <nl> <nl> deps = { <nl> " v8 / build " : <nl> - Var ( " chromium_url " ) + " / chromium / src / build . git " + " @ " + " 564be7572b31dc68e224657f3a3de2c342dc7818 " , <nl> + Var ( " chromium_url " ) + " / chromium / src / build . git " + " @ " + " 41581c8f0516ff2e210d373b195c0cee2ef6f056 " , <nl> " v8 / tools / gyp " : <nl> Var ( " chromium_url " ) + " / external / gyp . git " + " @ " + " eb296f67da078ec01f5e3a9ea9cdc6d26d680161 " , <nl> " v8 / third_party / icu " : <nl> deps = { <nl> " v8 / buildtools " : <nl> Var ( " chromium_url " ) + " / chromium / buildtools . git " + " @ " + " 7f2cacbbe274ef9df2c94452e05e8702c3ae65a9 " , <nl> " v8 / base / trace_event / common " : <nl> - Var ( " chromium_url " ) + " / chromium / src / base / trace_event / common . git " + " @ " + " 39a3450531fc73432e963db8668695d2e8f13053 " , <nl> + Var ( " chromium_url " ) + " / chromium / src / base / trace_event / common . git " + " @ " + " 65d1d42a5df6c0a563a6fdfa58a135679185e5d9 " , <nl> " v8 / third_party / jinja2 " : <nl> Var ( " chromium_url " ) + " / chromium / src / third_party / jinja2 . git " + " @ " + " d34383206fa42d52faa10bb9931d6d538f3a57e0 " , <nl> " v8 / third_party / markupsafe " : <nl> deps_os = { <nl> " v8 / third_party / android_tools " : <nl> Var ( " chromium_url " ) + " / android_tools . git " + " @ " + " 023e2f65409a2b7886b8d644d6a88542ead6cd0a " , <nl> " v8 / third_party / catapult " : <nl> - Var ( ' chromium_url ' ) + " / external / github . com / catapult - project / catapult . git " + " @ " + " d4f2d777c7aa4d9454a74afe92ff17e13da62380 " , <nl> + Var ( ' chromium_url ' ) + " / external / github . com / catapult - project / catapult . git " + " @ " + " 520dd376a20eb6ab41cd88a5dbfd56ee3d156d2f " , <nl> } , <nl> } <nl> <nl>
Update V8 DEPS .
v8/v8
68c6ce6707e96df480ca8be963b300bfaa63bf1c
2017-06-27T03:54:10Z
mmm a / src / python / grpcio / grpc / __init__ . py <nl> ppp b / src / python / grpcio / grpc / __init__ . py <nl> def details ( self ) : <nl> This method blocks until the value is available . <nl> <nl> Returns : <nl> - The bytes of the details of the RPC . <nl> + The details string of the RPC . <nl> " " " <nl> raise NotImplementedError ( ) <nl> <nl> def set_details ( self , details ) : <nl> details to transmit . <nl> <nl> Args : <nl> - details : The details bytes of the RPC to be transmitted to <nl> + details : The details string of the RPC to be transmitted to <nl> the invocation side of the RPC . <nl> " " " <nl> raise NotImplementedError ( ) <nl>
Document rpc details as string type
grpc/grpc
c41f81aeeb054ec436934c7cc1afeb1dee0a8581
2016-07-13T21:52:40Z
mmm a / third_party / onnx <nl> ppp b / third_party / onnx <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit ecac1c162485b3d6072eff73dbbc79fd5376c8ff <nl> + Subproject commit 6fe932a3e17a4aff39a54bd27c539bc9bf0f4df4 <nl>
[ auto ] Update onnx to 6fe932a - Replace unittest . skip with custom exception ( )
pytorch/pytorch
b6b2edb96fcf350d4ec31e6cc90b14de94f90790
2018-03-26T21:20:58Z
mmm a / fdbserver / DataDistribution . actor . cpp <nl> ppp b / fdbserver / DataDistribution . actor . cpp <nl> ACTOR Future < Reference < InitialDataDistribution > > getInitialDataDistribution ( Dat <nl> } <nl> } else { <nl> info . primarySrc = src ; <nl> - result - > primaryTeams . insert ( src ) ; <nl> + auto srcIter = team_cache . find ( src ) ; <nl> + if ( srcIter = = team_cache . end ( ) ) { <nl> + result - > primaryTeams . insert ( src ) ; <nl> + team_cache [ src ] = std : : pair < vector < UID > , vector < UID > > ( ) ; <nl> + } <nl> if ( dest . size ( ) ) { <nl> info . hasDest = true ; <nl> info . primaryDest = dest ; <nl> - result - > primaryTeams . insert ( dest ) ; <nl> + auto destIter = team_cache . find ( dest ) ; <nl> + if ( destIter = = team_cache . end ( ) ) { <nl> + result - > primaryTeams . insert ( dest ) ; <nl> + team_cache [ dest ] = std : : pair < vector < UID > , vector < UID > > ( ) ; <nl> + } <nl> } <nl> } <nl> result - > shards . push_back ( info ) ; <nl>
fix : the same team was being added multiple times to primaryTeams
apple/foundationdb
d12dac60ec9d503ad92a469f81339d45874485db
2018-07-12T19:10:18Z
new file mode 100644 <nl> index 000000000000 . . fe34fee02b03 <nl> mmm / dev / null <nl> ppp b / test / IRGen / async / run - thintothick - int64 - to - void . sil <nl> <nl> + / / RUN : % empty - directory ( % t ) <nl> + / / RUN : % target - build - swift - dylib ( % t / % target - library - name ( PrintShims ) ) % S / . . / . . / Inputs / print - shims . swift - module - name PrintShims - emit - module - emit - module - path % t / PrintShims . swiftmodule <nl> + / / RUN : % target - codesign % t / % target - library - name ( PrintShims ) <nl> + / / RUN : % target - build - swift - Xfrontend - enable - experimental - concurrency - parse - sil % s - emit - ir - I % t - L % t - lPrintShim | % FileCheck % s - - check - prefix = CHECK - LL <nl> + / / RUN : % target - build - swift - Xfrontend - enable - experimental - concurrency - parse - sil % s - module - name main - o % t / main - I % t - L % t - lPrintShims % target - rpath ( % t ) <nl> + / / RUN : % target - codesign % t / main <nl> + / / RUN : % target - run % t / main % t / % target - library - name ( PrintShims ) | % FileCheck % s <nl> + <nl> + / / REQUIRES : executable_test <nl> + / / REQUIRES : swift_test_mode_optimize_none <nl> + / / REQUIRES : concurrency <nl> + / / UNSUPPORTED : use_os_stdlib <nl> + <nl> + import Builtin <nl> + import Swift <nl> + import PrintShims <nl> + import _Concurrency <nl> + <nl> + sil public_external @ printInt64 : $ @ convention ( thin ) ( Int64 ) - > ( ) <nl> + <nl> + / / CHECK - LL : define { { ( dllexport ) ? } } { { ( protected ) ? } } swiftcc void @ afun2 ( % swift . task * { { % [ 0 - 9 ] + } } , % swift . executor * { { % [ 0 - 9 ] + } } , % swift . context * { { % [ 0 - 9 ] + } } ) { { # [ 0 - 9 ] * } } { <nl> + sil @ afun2 : $ @ async @ convention ( thin ) ( Int64 ) - > ( ) { <nl> + entry ( % int : $ Int64 ) : <nl> + % print = function_ref @ printInt64 : $ @ convention ( thin ) ( Int64 ) - > ( ) <nl> + % result = apply % print ( % int ) : $ @ convention ( thin ) ( Int64 ) - > ( ) / / CHECK : 9999 <nl> + return % result : $ ( ) <nl> + } <nl> + <nl> + / / CHECK - LL : define { { ( dllexport ) ? } } { { ( protected ) ? } } swiftcc void @ test_apply_of_thin_to_thick ( % swift . task * { { % [ 0 - 9 ] + } } , % swift . executor * { { % [ 0 - 9 ] + } } , % swift . context * { { % [ 0 - 9 ] + } } ) { { # [ 0 - 9 ] * } } { <nl> + sil @ test_apply_of_thin_to_thick : $ @ async @ convention ( thin ) ( ) - > ( ) { <nl> + entry : <nl> + % f = function_ref @ afun2 : $ @ async @ convention ( thin ) ( Int64 ) - > ( ) <nl> + % c = thin_to_thick_function % f : $ @ async @ convention ( thin ) ( Int64 ) - > ( ) to $ @ async @ callee_guaranteed ( Int64 ) - > ( ) <nl> + % int_literal = integer_literal $ Builtin . Int64 , 9999 <nl> + % int = struct $ Int64 ( % int_literal : $ Builtin . Int64 ) <nl> + % app = apply % c ( % int ) : $ @ async @ callee_guaranteed ( Int64 ) - > ( ) <nl> + % result = tuple ( ) <nl> + return % result : $ ( ) <nl> + } <nl> + <nl> + sil @ main : $ @ async @ convention ( c ) ( Int32 , UnsafeMutablePointer < Optional < UnsafeMutablePointer < Int8 > > > ) - > Int32 { <nl> + bb0 ( % argc : $ Int32 , % argv : $ UnsafeMutablePointer < Optional < UnsafeMutablePointer < Int8 > > > ) : <nl> + % test_apply_of_thin_to_thick = function_ref @ test_apply_of_thin_to_thick : $ @ async @ convention ( thin ) ( ) - > ( ) <nl> + % result = apply % test_apply_of_thin_to_thick ( ) : $ @ async @ convention ( thin ) ( ) - > ( ) <nl> + <nl> + % out_literal = integer_literal $ Builtin . Int32 , 0 <nl> + % out = struct $ Int32 ( % out_literal : $ Builtin . Int32 ) <nl> + return % out : $ Int32 <nl> + } <nl> mmm a / utils / build - script <nl> ppp b / utils / build - script <nl> def apply_default_arguments ( toolchain , args ) : <nl> elif args . android_arch = = " aarch64 " : <nl> args . stdlib_deployment_targets . append ( <nl> StdlibDeploymentTarget . Android . aarch64 . name ) <nl> + elif args . android_arch = = " x86_64 " : <nl> + args . stdlib_deployment_targets . append ( <nl> + StdlibDeploymentTarget . Android . x86_64 . name ) <nl> <nl> # Infer platform flags from manually - specified configure targets . <nl> # This doesn ' t apply to Darwin platforms , as they are <nl> mmm a / utils / build - script - impl <nl> ppp b / utils / build - script - impl <nl> function verify_host_is_supported ( ) { <nl> | watchsimulator - arm64 \ <nl> | watchos - armv7k \ <nl> | android - armv7 \ <nl> - | android - aarch64 ) <nl> + | android - aarch64 \ <nl> + | android - x86_64 ) <nl> ; ; <nl> * ) <nl> echo " Unknown host tools target : $ { host } " <nl> function set_build_options_for_host ( ) { <nl> SWIFT_HOST_TRIPLE = " armv7 - unknown - linux - androideabi " <nl> llvm_target_arch = " ARM " <nl> ; ; <nl> + android - x86_64 ) <nl> + SWIFT_HOST_TRIPLE = " x86_64 - unknown - linux - android $ { ANDROID_API_LEVEL } " <nl> + llvm_target_arch = " X86 " <nl> + ; ; <nl> linux - armv6 ) <nl> SWIFT_HOST_TRIPLE = " armv6 - unknown - linux - gnueabihf " <nl> llvm_target_arch = " ARM " <nl> mmm a / utils / build_swift / build_swift / driver_arguments . py <nl> ppp b / utils / build_swift / build_swift / driver_arguments . py <nl> def create_argument_parser ( ) : <nl> android . adb . commands . DEVICE_TEMP_DIR ) ) <nl> <nl> option ( ' - - android - arch ' , store , <nl> - choices = [ ' armv7 ' , ' aarch64 ' ] , <nl> + choices = [ ' armv7 ' , ' aarch64 ' , ' x86_64 ' ] , <nl> default = ' armv7 ' , <nl> - help = ' The Android target architecture when building for Android . ' <nl> - ' Currently only armv7 and aarch64 are supported . ' <nl> + help = ' The target architecture when building for Android . ' <nl> + ' Currently , only armv7 , aarch64 , and x86_64 are supported . ' <nl> ' % ( default ) s is the default . ' ) <nl> <nl> # mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> mmm a / utils / swift_build_support / swift_build_support / targets . py <nl> ppp b / utils / swift_build_support / swift_build_support / targets . py <nl> class StdlibDeploymentTarget ( object ) : <nl> <nl> Cygwin = Platform ( " cygwin " , archs = [ " x86_64 " ] ) <nl> <nl> - Android = AndroidPlatform ( " android " , archs = [ " armv7 " , " aarch64 " ] ) <nl> + Android = AndroidPlatform ( " android " , archs = [ " armv7 " , " aarch64 " , " x86_64 " ] ) <nl> <nl> Windows = Platform ( " windows " , archs = [ " x86_64 " ] ) <nl> <nl>
Merge remote - tracking branch ' origin / main ' into next
apple/swift
6b5bf3cf65559f0eb2c0f2676b0a79707035597d
2020-11-12T19:43:40Z
mmm a / tensorflow / contrib / lite / build_def . bzl <nl> ppp b / tensorflow / contrib / lite / build_def . bzl <nl> def generated_test_models ( ) : <nl> " expand_dims " , <nl> " floor " , <nl> " floor_div " , <nl> + " floor_mod " , <nl> " fully_connected " , <nl> " fused_batch_norm " , <nl> " gather " , <nl> mmm a / tensorflow / contrib / lite / kernels / BUILD <nl> ppp b / tensorflow / contrib / lite / kernels / BUILD <nl> cc_library ( <nl> " fake_quant . cc " , <nl> " floor . cc " , <nl> " floor_div . cc " , <nl> + " floor_mod . cc " , <nl> " fully_connected . cc " , <nl> " gather . cc " , <nl> " hashtable_lookup . cc " , <nl> tf_cc_test ( <nl> ] , <nl> ) <nl> <nl> + tf_cc_test ( <nl> + name = " floor_mod_test " , <nl> + size = " small " , <nl> + srcs = [ " floor_mod_test . cc " ] , <nl> + tags = [ " tflite_not_portable_ios " ] , <nl> + deps = [ <nl> + " : builtin_ops " , <nl> + " / / tensorflow / contrib / lite : builtin_op_data " , <nl> + " / / tensorflow / contrib / lite : framework " , <nl> + " / / tensorflow / contrib / lite / kernels : test_util " , <nl> + " @ com_google_googletest / / : gtest " , <nl> + ] , <nl> + ) <nl> + <nl> filegroup ( <nl> name = " all_files " , <nl> srcs = glob ( <nl> new file mode 100644 <nl> index 0000000000000 . . 3d31cca396970 <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / lite / kernels / floor_mod . cc <nl> <nl> + / * Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + # include < functional > <nl> + # include < type_traits > <nl> + # include " tensorflow / contrib / lite / c / c_api_internal . h " <nl> + # include " tensorflow / contrib / lite / kernels / internal / reference / reference_ops . h " <nl> + # include " tensorflow / contrib / lite / kernels / internal / tensor . h " <nl> + # include " tensorflow / contrib / lite / kernels / kernel_util . h " <nl> + # include " tensorflow / contrib / lite / kernels / op_macros . h " <nl> + <nl> + / / TODO ( b / 117523611 ) : We should factor out a binary_op and put binary ops there . <nl> + namespace tflite { <nl> + namespace ops { <nl> + namespace builtin { <nl> + namespace floor_mod { <nl> + namespace { <nl> + <nl> + / / Input / output tensor index . <nl> + constexpr int kInputTensor1 = 0 ; <nl> + constexpr int kInputTensor2 = 1 ; <nl> + constexpr int kOutputTensor = 0 ; <nl> + <nl> + / / Op data for floor_mod op . <nl> + struct OpData { <nl> + bool requires_broadcast ; <nl> + } ; <nl> + <nl> + struct FloatMod { <nl> + float operator ( ) ( const float lhs , const float rhs ) const { <nl> + return std : : fmod ( lhs , rhs ) ; <nl> + } <nl> + } ; <nl> + <nl> + / / TODO ( b / 117912007 ) : Move the implementation to reference_ops . h <nl> + / / TODO ( b / 117912880 ) : Support quantization . <nl> + template < typename T > <nl> + T FloorMod ( T input1 , T input2 ) { <nl> + using ModFunc = typename std : : conditional < std : : is_integral < T > : : value , <nl> + std : : modulus < T > , FloatMod > : : type ; <nl> + <nl> + ModFunc mod_func ; <nl> + T trunc_mod = mod_func ( input1 , input2 ) ; <nl> + return ( input1 < T ( 0 ) ) = = ( input2 < T ( 0 ) ) <nl> + ? trunc_mod <nl> + : mod_func ( trunc_mod + input2 , input2 ) ; <nl> + } <nl> + <nl> + void * Init ( TfLiteContext * context , const char * buffer , size_t length ) { <nl> + auto * data = new OpData ; <nl> + data - > requires_broadcast = false ; <nl> + return data ; <nl> + } <nl> + <nl> + void Free ( TfLiteContext * context , void * buffer ) { <nl> + delete reinterpret_cast < OpData * > ( buffer ) ; <nl> + } <nl> + <nl> + TfLiteStatus Prepare ( TfLiteContext * context , TfLiteNode * node ) { <nl> + TF_LITE_ENSURE_EQ ( context , NumInputs ( node ) , 2 ) ; <nl> + TF_LITE_ENSURE_EQ ( context , NumOutputs ( node ) , 1 ) ; <nl> + <nl> + / / Reinterprete the opaque data provided by user . <nl> + OpData * data = reinterpret_cast < OpData * > ( node - > user_data ) ; <nl> + <nl> + const TfLiteTensor * input1 = GetInput ( context , node , kInputTensor1 ) ; <nl> + const TfLiteTensor * input2 = GetInput ( context , node , kInputTensor2 ) ; <nl> + TfLiteTensor * output = GetOutput ( context , node , kOutputTensor ) ; <nl> + <nl> + TF_LITE_ENSURE_EQ ( context , input1 - > type , input2 - > type ) ; <nl> + <nl> + const TfLiteType type = input1 - > type ; <nl> + if ( type ! = kTfLiteInt32 & & type ! = kTfLiteFloat32 ) { <nl> + context - > ReportError ( context , <nl> + " Currently floor_mod only supports int32 and float . " ) ; <nl> + return kTfLiteError ; <nl> + } <nl> + output - > type = type ; <nl> + <nl> + data - > requires_broadcast = ! HaveSameShapes ( input1 , input2 ) ; <nl> + <nl> + TfLiteIntArray * output_size = nullptr ; <nl> + if ( data - > requires_broadcast ) { <nl> + TF_LITE_ENSURE_OK ( context , CalculateShapeForBroadcast ( <nl> + context , input1 , input2 , & output_size ) ) ; <nl> + } else { <nl> + output_size = TfLiteIntArrayCopy ( input1 - > dims ) ; <nl> + } <nl> + <nl> + return context - > ResizeTensor ( context , output , output_size ) ; <nl> + } <nl> + <nl> + template < typename T > <nl> + TfLiteStatus EvalImpl ( TfLiteContext * context , bool requires_broadcast , <nl> + const TfLiteTensor * input1 , const TfLiteTensor * input2 , <nl> + TfLiteTensor * output ) { <nl> + const T * denominator_data = GetTensorData < T > ( input2 ) ; <nl> + <nl> + if ( input2 - > type = = kTfLiteInt32 ) { <nl> + / / Validate the denominator only for integer . <nl> + const int num_elements = NumElements ( input2 ) ; <nl> + for ( int i = 0 ; i < num_elements ; + + i ) { <nl> + if ( denominator_data [ i ] = = 0 ) { <nl> + context - > ReportError ( context , " Division by 0 " ) ; <nl> + return kTfLiteError ; <nl> + } <nl> + } <nl> + } <nl> + if ( requires_broadcast ) { <nl> + reference_ops : : BroadcastBinaryFunction4DSlow < T , T , T > ( <nl> + GetTensorShape ( input1 ) , GetTensorData < T > ( input1 ) , <nl> + GetTensorShape ( input2 ) , denominator_data , GetTensorShape ( output ) , <nl> + GetTensorData < T > ( output ) , FloorMod < T > ) ; <nl> + } else { <nl> + reference_ops : : BinaryFunction < T , T , T > ( <nl> + GetTensorShape ( input1 ) , GetTensorData < T > ( input1 ) , <nl> + GetTensorShape ( input2 ) , GetTensorData < T > ( input2 ) , <nl> + GetTensorShape ( output ) , GetTensorData < T > ( output ) , FloorMod < T > ) ; <nl> + } <nl> + <nl> + return kTfLiteOk ; <nl> + } <nl> + <nl> + TfLiteStatus Eval ( TfLiteContext * context , TfLiteNode * node ) { <nl> + OpData * data = reinterpret_cast < OpData * > ( node - > user_data ) ; <nl> + <nl> + const TfLiteTensor * input1 = GetInput ( context , node , kInputTensor1 ) ; <nl> + const TfLiteTensor * input2 = GetInput ( context , node , kInputTensor2 ) ; <nl> + TfLiteTensor * output = GetOutput ( context , node , kOutputTensor ) ; <nl> + <nl> + switch ( input1 - > type ) { <nl> + case kTfLiteInt32 : { <nl> + return EvalImpl < int32_t > ( context , data - > requires_broadcast , input1 , <nl> + input2 , output ) ; <nl> + } <nl> + case kTfLiteFloat32 : { <nl> + return EvalImpl < float > ( context , data - > requires_broadcast , input1 , input2 , <nl> + output ) ; <nl> + } <nl> + default : { <nl> + context - > ReportError ( <nl> + context , " Currently floor_mod only supports int32 and float . " ) ; <nl> + return kTfLiteError ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + } / / namespace <nl> + } / / namespace floor_mod <nl> + <nl> + TfLiteRegistration * Register_FLOOR_MOD ( ) { <nl> + / / Init , Free , Prepare , Eval are satisfying the Interface required by <nl> + / / TfLiteRegistration . <nl> + static TfLiteRegistration r = { floor_mod : : Init , floor_mod : : Free , <nl> + floor_mod : : Prepare , floor_mod : : Eval } ; <nl> + return & r ; <nl> + } <nl> + <nl> + } / / namespace builtin <nl> + } / / namespace ops <nl> + } / / namespace tflite <nl> new file mode 100644 <nl> index 0000000000000 . . c581a5393648d <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / lite / kernels / floor_mod_test . cc <nl> <nl> + / * Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + # include < gtest / gtest . h > <nl> + # include " tensorflow / contrib / lite / interpreter . h " <nl> + # include " tensorflow / contrib / lite / kernels / register . h " <nl> + # include " tensorflow / contrib / lite / kernels / test_util . h " <nl> + # include " tensorflow / contrib / lite / model . h " <nl> + <nl> + namespace tflite { <nl> + namespace { <nl> + <nl> + using : : testing : : ElementsAre ; <nl> + <nl> + template < typename T > <nl> + class FloorModModel : public SingleOpModel { <nl> + public : <nl> + FloorModModel ( const TensorData & input1 , const TensorData & input2 , <nl> + const TensorData & output ) { <nl> + input1_ = AddInput ( input1 ) ; <nl> + input2_ = AddInput ( input2 ) ; <nl> + output_ = AddOutput ( output ) ; <nl> + SetBuiltinOp ( BuiltinOperator_FLOOR_MOD , BuiltinOptions_FloorModOptions , <nl> + CreateFloorModOptions ( builder_ ) . Union ( ) ) ; <nl> + BuildInterpreter ( { GetShape ( input1_ ) , GetShape ( input2_ ) } ) ; <nl> + } <nl> + <nl> + int input1 ( ) { return input1_ ; } <nl> + int input2 ( ) { return input2_ ; } <nl> + <nl> + std : : vector < T > GetOutput ( ) { return ExtractVector < T > ( output_ ) ; } <nl> + std : : vector < int > GetOutputShape ( ) { return GetTensorShape ( output_ ) ; } <nl> + <nl> + private : <nl> + int input1_ ; <nl> + int input2_ ; <nl> + int output_ ; <nl> + } ; <nl> + <nl> + TEST ( FloorModModel , Simple ) { <nl> + FloorModModel < int32_t > model ( { TensorType_INT32 , { 1 , 2 , 2 , 1 } } , <nl> + { TensorType_INT32 , { 1 , 2 , 2 , 1 } } , <nl> + { TensorType_INT32 , { } } ) ; <nl> + model . PopulateTensor < int32_t > ( model . input1 ( ) , { 10 , 9 , 11 , 3 } ) ; <nl> + model . PopulateTensor < int32_t > ( model . input2 ( ) , { 2 , 2 , 3 , 4 } ) ; <nl> + model . Invoke ( ) ; <nl> + EXPECT_THAT ( model . GetOutputShape ( ) , ElementsAre ( 1 , 2 , 2 , 1 ) ) ; <nl> + EXPECT_THAT ( model . GetOutput ( ) , ElementsAre ( 0 , 1 , 2 , 3 ) ) ; <nl> + } <nl> + <nl> + TEST ( FloorModModel , NegativeValue ) { <nl> + FloorModModel < int32_t > model ( { TensorType_INT32 , { 1 , 2 , 2 , 1 } } , <nl> + { TensorType_INT32 , { 1 , 2 , 2 , 1 } } , <nl> + { TensorType_INT32 , { } } ) ; <nl> + model . PopulateTensor < int32_t > ( model . input1 ( ) , { 10 , - 9 , - 11 , 7 } ) ; <nl> + model . PopulateTensor < int32_t > ( model . input2 ( ) , { 2 , 2 , - 3 , - 4 } ) ; <nl> + model . Invoke ( ) ; <nl> + EXPECT_THAT ( model . GetOutputShape ( ) , ElementsAre ( 1 , 2 , 2 , 1 ) ) ; <nl> + EXPECT_THAT ( model . GetOutput ( ) , ElementsAre ( 0 , 1 , - 2 , - 1 ) ) ; <nl> + } <nl> + <nl> + TEST ( FloorModModel , BroadcastFloorMod ) { <nl> + FloorModModel < int32_t > model ( { TensorType_INT32 , { 1 , 2 , 2 , 1 } } , <nl> + { TensorType_INT32 , { 1 } } , { TensorType_INT32 , { } } ) ; <nl> + model . PopulateTensor < int32_t > ( model . input1 ( ) , { 10 , - 9 , - 11 , 7 } ) ; <nl> + model . PopulateTensor < int32_t > ( model . input2 ( ) , { - 3 } ) ; <nl> + model . Invoke ( ) ; <nl> + EXPECT_THAT ( model . GetOutputShape ( ) , ElementsAre ( 1 , 2 , 2 , 1 ) ) ; <nl> + EXPECT_THAT ( model . GetOutput ( ) , ElementsAre ( - 2 , 0 , - 2 , - 2 ) ) ; <nl> + } <nl> + <nl> + TEST ( FloorModModel , FloatSimple ) { <nl> + FloorModModel < float > model ( { TensorType_FLOAT32 , { 1 , 2 , 2 , 1 } } , <nl> + { TensorType_FLOAT32 , { 1 , 2 , 2 , 1 } } , <nl> + { TensorType_FLOAT32 , { } } ) ; <nl> + model . PopulateTensor < float > ( model . input1 ( ) , { 10 , 9 , 11 , 3 } ) ; <nl> + model . PopulateTensor < float > ( model . input2 ( ) , { 2 , 2 , 3 , 4 } ) ; <nl> + model . Invoke ( ) ; <nl> + EXPECT_THAT ( model . GetOutputShape ( ) , ElementsAre ( 1 , 2 , 2 , 1 ) ) ; <nl> + EXPECT_THAT ( model . GetOutput ( ) , ElementsAre ( 0 , 1 , 2 , 3 ) ) ; <nl> + } <nl> + <nl> + TEST ( FloorModModel , FloatNegativeValue ) { <nl> + FloorModModel < float > model ( { TensorType_FLOAT32 , { 1 , 2 , 2 , 1 } } , <nl> + { TensorType_FLOAT32 , { 1 , 2 , 2 , 1 } } , <nl> + { TensorType_FLOAT32 , { } } ) ; <nl> + model . PopulateTensor < float > ( model . input1 ( ) , { 10 , - 9 , - 11 , 7 } ) ; <nl> + model . PopulateTensor < float > ( model . input2 ( ) , { 2 , 2 , - 3 , - 4 } ) ; <nl> + model . Invoke ( ) ; <nl> + EXPECT_THAT ( model . GetOutputShape ( ) , ElementsAre ( 1 , 2 , 2 , 1 ) ) ; <nl> + EXPECT_THAT ( model . GetOutput ( ) , ElementsAre ( 0 , 1 , - 2 , - 1 ) ) ; <nl> + } <nl> + <nl> + TEST ( FloorModModel , FloatBroadcastFloorMod ) { <nl> + FloorModModel < float > model ( { TensorType_FLOAT32 , { 1 , 2 , 2 , 1 } } , <nl> + { TensorType_FLOAT32 , { 1 } } , <nl> + { TensorType_FLOAT32 , { } } ) ; <nl> + model . PopulateTensor < float > ( model . input1 ( ) , { 10 , - 9 , - 11 , 7 } ) ; <nl> + model . PopulateTensor < float > ( model . input2 ( ) , { - 3 } ) ; <nl> + model . Invoke ( ) ; <nl> + EXPECT_THAT ( model . GetOutputShape ( ) , ElementsAre ( 1 , 2 , 2 , 1 ) ) ; <nl> + EXPECT_THAT ( model . GetOutput ( ) , ElementsAre ( - 2 , 0 , - 2 , - 2 ) ) ; <nl> + } <nl> + <nl> + } / / namespace <nl> + } / / namespace tflite <nl> + <nl> + int main ( int argc , char * * argv ) { <nl> + : : tflite : : LogToStderr ( ) ; <nl> + : : testing : : InitGoogleTest ( & argc , argv ) ; <nl> + return RUN_ALL_TESTS ( ) ; <nl> + } <nl> mmm a / tensorflow / contrib / lite / kernels / register . cc <nl> ppp b / tensorflow / contrib / lite / kernels / register . cc <nl> TfLiteRegistration * Register_UNPACK ( ) ; <nl> TfLiteRegistration * Register_FLOOR_DIV ( ) ; <nl> TfLiteRegistration * Register_SQUARE ( ) ; <nl> TfLiteRegistration * Register_ZEROS_LIKE ( ) ; <nl> + TfLiteRegistration * Register_FLOOR_MOD ( ) ; <nl> <nl> TfLiteStatus UnsupportedTensorFlowOp ( TfLiteContext * context , TfLiteNode * node ) { <nl> context - > ReportError ( <nl> BuiltinOpResolver : : BuiltinOpResolver ( ) { <nl> AddBuiltin ( BuiltinOperator_FLOOR_DIV , Register_FLOOR_DIV ( ) ) ; <nl> AddBuiltin ( BuiltinOperator_SQUARE , Register_SQUARE ( ) ) ; <nl> AddBuiltin ( BuiltinOperator_ZEROS_LIKE , Register_ZEROS_LIKE ( ) ) ; <nl> + AddBuiltin ( BuiltinOperator_FLOOR_MOD , Register_FLOOR_MOD ( ) ) ; <nl> <nl> / / TODO ( andrewharp , ahentz ) : Move these somewhere more appropriate so that <nl> / / custom ops aren ' t always included by default . <nl> mmm a / tensorflow / contrib / lite / testing / generate_examples . py <nl> ppp b / tensorflow / contrib / lite / testing / generate_examples . py <nl> def make_floor_div_tests ( zip_path ) : <nl> make_binary_op_tests ( zip_path , tf . floor_div ) <nl> <nl> <nl> + def make_floor_mod_tests ( zip_path ) : <nl> + make_binary_op_tests ( zip_path , tf . floormod ) <nl> + <nl> + <nl> def make_gather_tests ( zip_path ) : <nl> " " " Make a set of tests to do gather . " " " <nl> <nl> mmm a / tensorflow / contrib / lite / testing / generated_examples_zip_test . cc <nl> ppp b / tensorflow / contrib / lite / testing / generated_examples_zip_test . cc <nl> std : : map < string , string > kBrokenTests = { <nl> / / activation = True . The tests are failing since Relu doesn ' t support int32 . <nl> { R " ( ^ \ / div . * activation = True . * dtype = tf \ . int32 ) " , " 112968789 " } , <nl> { R " ( ^ \ / floor_div . * activation = True . * dtype = tf \ . int32 ) " , " 112968789 " } , <nl> + { R " ( ^ \ / floor_mod . * activation = True . * dtype = tf \ . int32 ) " , " 112968789 " } , <nl> } ; <nl> <nl> / / Allows test data to be unarchived into a temporary directory and makes <nl> mmm a / tensorflow / contrib / lite / toco / export_tensorflow . cc <nl> ppp b / tensorflow / contrib / lite / toco / export_tensorflow . cc <nl> void ConvertFloorDivOperator ( const Model & model , const FloorDivOperator & src_op , <nl> GetTensorFlowDataType ( model , src_op . inputs [ 0 ] ) ) ; <nl> } <nl> <nl> + void ConvertFloorModOperator ( const Model & model , const FloorModOperator & src_op , <nl> + GraphDef * tensorflow_graph ) { <nl> + tensorflow : : NodeDef * floor_mod_op = tensorflow_graph - > add_node ( ) ; <nl> + floor_mod_op - > set_op ( " FloorMod " ) ; <nl> + floor_mod_op - > set_name ( src_op . outputs [ 0 ] ) ; <nl> + DCHECK_EQ ( src_op . inputs . size ( ) , 2 ) ; <nl> + * floor_mod_op - > add_input ( ) = src_op . inputs [ 0 ] ; <nl> + * floor_mod_op - > add_input ( ) = src_op . inputs [ 1 ] ; <nl> + ( * floor_mod_op - > mutable_attr ( ) ) [ " T " ] . set_type ( <nl> + GetTensorFlowDataType ( model , src_op . inputs [ 0 ] ) ) ; <nl> + } <nl> + <nl> void ConvertExpandDimsOperator ( const Model & model , <nl> const ExpandDimsOperator & src_op , <nl> GraphDef * tensorflow_graph ) { <nl> void ConvertOperator ( const Model & model , const Operator & src_op , <nl> } else if ( src_op . type = = OperatorType : : kFloorDiv ) { <nl> ConvertFloorDivOperator ( model , static_cast < const FloorDivOperator & > ( src_op ) , <nl> tensorflow_graph ) ; <nl> + } else if ( src_op . type = = OperatorType : : kFloorMod ) { <nl> + ConvertFloorModOperator ( model , static_cast < const FloorModOperator & > ( src_op ) , <nl> + tensorflow_graph ) ; <nl> } else if ( src_op . type = = OperatorType : : kExpandDims ) { <nl> ConvertExpandDimsOperator ( model , <nl> static_cast < const ExpandDimsOperator & > ( src_op ) , <nl> mmm a / tensorflow / contrib / lite / toco / tflite / operator . cc <nl> ppp b / tensorflow / contrib / lite / toco / tflite / operator . cc <nl> std : : vector < std : : unique_ptr < BaseOperator > > BuildOperatorList ( <nl> " LOGICAL_NOT " , OperatorType : : kLogicalNot ) ) ; <nl> ops . emplace_back ( new SimpleOperator < FloorDivOperator > ( <nl> " FLOOR_DIV " , OperatorType : : kFloorDiv ) ) ; <nl> + ops . emplace_back ( new SimpleOperator < FloorModOperator > ( <nl> + " FLOOR_MOD " , OperatorType : : kFloorMod ) ) ; <nl> / / Element - wise operator <nl> ops . push_back ( <nl> MakeUnique < SimpleOperator < SinOperator > > ( " SIN " , OperatorType : : kSin ) ) ; <nl> mmm a / tensorflow / contrib / lite / toco / tflite / operator_test . cc <nl> ppp b / tensorflow / contrib / lite / toco / tflite / operator_test . cc <nl> TEST_F ( OperatorTest , SimpleOperators ) { <nl> OperatorType : : kSquare ) ; <nl> CheckSimpleOperator < TensorFlowZerosLikeOperator > ( " ZEROS_LIKE " , <nl> OperatorType : : kZerosLike ) ; <nl> + CheckSimpleOperator < FloorModOperator > ( " FLOOR_MOD " , OperatorType : : kFloorMod ) ; <nl> } <nl> <nl> TEST_F ( OperatorTest , BuiltinAdd ) { <nl>
Implementation of floor_mod
tensorflow/tensorflow
b6d59641acc24fa7a19e41899c37770c6707ccdc
2018-10-19T06:55:32Z
mmm a / lib / SILOptimizer / SILCombiner / SILCombiner . h <nl> ppp b / lib / SILOptimizer / SILCombiner / SILCombiner . h <nl> class SILCombiner : <nl> private : <nl> FullApplySite rewriteApplyCallee ( FullApplySite apply , SILValue callee ) ; <nl> <nl> - bool canReplaceArg ( FullApplySite Apply , const ConcreteExistentialInfo & CEI , <nl> - unsigned ArgIdx ) ; <nl> - SILInstruction * createApplyWithConcreteType ( <nl> - FullApplySite Apply , <nl> - const llvm : : SmallDenseMap < unsigned , const ConcreteExistentialInfo * > <nl> - & CEIs , <nl> - SILBuilderContext & BuilderCtx ) ; <nl> + SILInstruction * createApplyWithConcreteType ( FullApplySite Apply , <nl> + const ConcreteExistentialInfo & CEI , <nl> + SILBuilderContext & BuilderCtx ) ; <nl> <nl> / / Common utility function to replace the WitnessMethodInst using a <nl> / / BuilderCtx . <nl> mmm a / lib / SILOptimizer / SILCombiner / SILCombinerApplyVisitors . cpp <nl> ppp b / lib / SILOptimizer / SILCombiner / SILCombinerApplyVisitors . cpp <nl> SILCombiner : : propagateSoleConformingType ( FullApplySite Apply , <nl> SILBuilderContext BuilderCtx ( M , Builder . getTrackingList ( ) ) ; <nl> replaceWitnessMethodInst ( WMI , BuilderCtx , ConcreteType , <nl> * ( CEI . ExistentialSubs . getConformances ( ) . begin ( ) ) ) ; <nl> - / / Construct the map for Self to be used for createApplyWithConcreteType . <nl> - llvm : : SmallDenseMap < unsigned , const ConcreteExistentialInfo * > CEIs ; <nl> - CEIs . insert ( std : : pair < unsigned , const ConcreteExistentialInfo * > ( <nl> - Apply . getCalleeArgIndex ( Apply . getSelfArgumentOperand ( ) ) , & CEI ) ) ; <nl> / / / Create the new apply instruction using the concrete type . <nl> - auto * NewAI = createApplyWithConcreteType ( Apply , CEIs , BuilderCtx ) ; <nl> + auto * NewAI = createApplyWithConcreteType ( Apply , CEI , BuilderCtx ) ; <nl> return NewAI ; <nl> } <nl> <nl> SILCombiner : : propagateSoleConformingType ( FullApplySite Apply , <nl> / / / return true if the argument can be replaced by a copy of its value . <nl> / / / <nl> / / / FIXME : remove this helper when we can assume SIL opaque values . <nl> - static bool canReplaceCopiedArg ( FullApplySite Apply , <nl> + static bool canReplaceCopiedSelf ( FullApplySite Apply , <nl> SILInstruction * InitExistential , <nl> - DominanceAnalysis * DA , unsigned ArgIdx ) { <nl> - / / If the witness method mutates Arg , we cannot replace Arg with <nl> + DominanceAnalysis * DA ) { <nl> + / / If the witness method mutates self , we cannot replace self with <nl> / / the source of a copy . Otherwise the call would modify another value than <nl> - / / the original argument . <nl> - if ( Apply . getOrigCalleeType ( ) - > getParameters ( ) [ ArgIdx ] . isIndirectMutating ( ) ) <nl> + / / the original self . <nl> + if ( Apply . getOrigCalleeType ( ) - > getSelfParameter ( ) . isIndirectMutating ( ) ) <nl> return false ; <nl> <nl> auto * DT = DA - > get ( Apply . getFunction ( ) ) ; <nl> static bool canReplaceCopiedArg ( FullApplySite Apply , <nl> return true ; <nl> } <nl> <nl> - / / Check the legal conditions under which a Arg parameter ( specified as ArgIdx ) <nl> - / / can be replaced with a concrete type . Concrete type info is passed as CEI <nl> - / / argument . <nl> - bool SILCombiner : : canReplaceArg ( FullApplySite Apply , <nl> - const ConcreteExistentialInfo & CEI , <nl> - unsigned ArgIdx ) { <nl> - <nl> - / / Don ' t specialize apply instructions that return the callee ' s Arg type , <nl> - / / because this optimization does not know how to substitute types in the <nl> - / / users of this apply . In the function type substitution below , all <nl> - / / references to OpenedArchetype will be substituted . So walk to type to <nl> - / / find all possible references , such as returning Optional < Arg > . <nl> - if ( Apply . getType ( ) . getASTType ( ) . findIf ( <nl> - [ & CEI ] ( Type t ) - > bool { return t - > isEqual ( CEI . OpenedArchetype ) ; } ) ) { <nl> - return false ; <nl> - } <nl> - / / Bail out if any other arguments or indirect result that refer to the <nl> - / / OpenedArchetype . The following optimization substitutes all occurrences <nl> - / / of OpenedArchetype in the function signature , but will only rewrite the <nl> - / / Arg operand . <nl> - / / <nl> - / / Note that the language does not allow Self to occur in contravariant <nl> - / / position . However , SIL does allow this and it can happen as a result of <nl> - / / upstream transformations . Since this is bail - out logic , it must handle <nl> - / / all verifiable SIL . <nl> - <nl> - / / This bailout check is also needed for non - Self arguments [ including Self ] . <nl> - unsigned NumApplyArgs = Apply . getNumArguments ( ) ; <nl> - for ( unsigned Idx = 0 ; Idx < NumApplyArgs ; Idx + + ) { <nl> - if ( Idx = = ArgIdx ) <nl> - continue ; <nl> - if ( Apply . getArgument ( Idx ) - > getType ( ) . getASTType ( ) . findIf ( <nl> - [ & CEI ] ( Type t ) - > bool { <nl> - return t - > isEqual ( CEI . OpenedArchetype ) ; <nl> - } ) ) { <nl> - return false ; <nl> - } <nl> - } <nl> - / / The apply can only be rewritten in terms of the concrete value if it is <nl> - / / legal to pass that value as the Arg argument . <nl> - if ( CEI . isCopied & & ( ! CEI . InitExistential | | <nl> - ! canReplaceCopiedArg ( Apply , CEI . InitExistential , DA , ArgIdx ) ) ) { <nl> - return false ; <nl> - } <nl> - / / It is safe to replace Arg . <nl> - return true ; <nl> - } <nl> - <nl> / / / Rewrite the given method apply instruction in terms of the provided conrete <nl> / / / type information . <nl> / / / <nl> bool SILCombiner : : canReplaceArg ( FullApplySite Apply , <nl> / / / FIXME : Protocol methods ( witness or default ) that return Self will be given <nl> / / / a new return type . This implementation fails to update the type signature of <nl> / / / SSA uses in those cases . Currently we bail out on methods that return Self . <nl> - SILInstruction * SILCombiner : : createApplyWithConcreteType ( <nl> - FullApplySite Apply , <nl> - const llvm : : SmallDenseMap < unsigned , const ConcreteExistentialInfo * > & CEIs , <nl> - SILBuilderContext & BuilderCtx ) { <nl> - <nl> - / / Ensure that the callee is polymorphic . <nl> + SILInstruction * <nl> + SILCombiner : : createApplyWithConcreteType ( FullApplySite Apply , <nl> + const ConcreteExistentialInfo & CEI , <nl> + SILBuilderContext & BuilderCtx ) { <nl> assert ( Apply . getOrigCalleeType ( ) - > isPolymorphic ( ) ) ; <nl> <nl> - / / Create the new set of arguments to apply including their substitutions . <nl> - SubstitutionMap NewCallSubs = Apply . getSubstitutionMap ( ) ; <nl> - SmallVector < SILValue , 8 > NewArgs ; <nl> - unsigned NumApplyArgs = Apply . getNumArguments ( ) ; <nl> - bool UpdatedArgs = false ; <nl> - for ( unsigned ArgIdx = 0 ; ArgIdx < NumApplyArgs ; ArgIdx + + ) { <nl> - auto ArgIt = CEIs . find ( ArgIdx ) ; <nl> - if ( ArgIt = = CEIs . end ( ) ) { <nl> - / / Use the old argument if it does not have a valid concrete existential . <nl> - NewArgs . push_back ( Apply . getArgument ( ArgIdx ) ) ; <nl> - continue ; <nl> - } <nl> - auto * CEI = ArgIt - > second ; <nl> - / / Check for Arg ' s concrete type propagation legality . <nl> - if ( ! canReplaceArg ( Apply , * CEI , ArgIdx ) ) { <nl> - NewArgs . push_back ( Apply . getArgument ( ArgIdx ) ) ; <nl> - continue ; <nl> + / / Don ' t specialize apply instructions that return the callee ' s Self type , <nl> + / / because this optimization does not know how to substitute types in the <nl> + / / users of this apply . In the function type substitution below , all <nl> + / / references to OpenedArchetype will be substituted . So walk to type to find <nl> + / / all possible references , such as returning Optional < Self > . <nl> + if ( Apply . getType ( ) . getASTType ( ) . findIf ( <nl> + [ & CEI ] ( Type t ) - > bool { return t - > isEqual ( CEI . OpenedArchetype ) ; } ) ) { <nl> + return nullptr ; <nl> + } <nl> + / / Bail out if any non - self arguments or indirect result that refer to the <nl> + / / OpenedArchetype . The following optimization substitutes all occurrences of <nl> + / / OpenedArchetype in the function signature , but will only rewrite the self <nl> + / / operand . <nl> + / / <nl> + / / Note that the language does not allow Self to occur in contravariant <nl> + / / position . However , SIL does allow this and it can happen as a result of <nl> + / / upstream transformations . Since this is bail - out logic , it must handle all <nl> + / / verifiable SIL . <nl> + for ( auto Arg : Apply . getArgumentsWithoutSelf ( ) ) { <nl> + if ( Arg - > getType ( ) . getASTType ( ) . findIf ( [ & CEI ] ( Type t ) - > bool { <nl> + return t - > isEqual ( CEI . OpenedArchetype ) ; <nl> + } ) ) { <nl> + return nullptr ; <nl> } <nl> - UpdatedArgs = true ; <nl> - / / Ensure that we have a concrete value to propagate . <nl> - assert ( CEI - > ConcreteValue ) ; <nl> - NewArgs . push_back ( CEI - > ConcreteValue ) ; <nl> - / / Form a new set of substitutions where the argument is <nl> - / / replaced with a concrete type . <nl> - NewCallSubs = NewCallSubs . subst ( <nl> - [ & ] ( SubstitutableType * type ) - > Type { <nl> - if ( type = = CEI - > OpenedArchetype ) <nl> - return CEI - > ConcreteType ; <nl> - return type ; <nl> - } , <nl> - [ & ] ( CanType origTy , Type substTy , <nl> - ProtocolDecl * proto ) - > Optional < ProtocolConformanceRef > { <nl> - if ( origTy - > isEqual ( CEI - > OpenedArchetype ) ) { <nl> - assert ( substTy - > isEqual ( CEI - > ConcreteType ) ) ; <nl> - / / Do a conformance lookup on this witness requirement using the <nl> - / / existential ' s conformances . The witness requirement may be a <nl> - / / base type of the existential ' s requirements . <nl> - return CEI - > lookupExistentialConformance ( proto ) ; <nl> - } <nl> - return ProtocolConformanceRef ( proto ) ; <nl> - } ) ; <nl> } <nl> - <nl> - if ( ! UpdatedArgs ) <nl> + / / The apply can only be rewritten in terms of the concrete value if it is <nl> + / / legal to pass that value as the self argument . <nl> + if ( CEI . isCopied & & ( ! CEI . InitExistential | | <nl> + ! canReplaceCopiedSelf ( Apply , CEI . InitExistential , DA ) ) ) { <nl> return nullptr ; <nl> + } <nl> + <nl> + / / Create a set of arguments . <nl> + SmallVector < SILValue , 8 > NewArgs ; <nl> + for ( auto Arg : Apply . getArgumentsWithoutSelf ( ) ) { <nl> + NewArgs . push_back ( Arg ) ; <nl> + } <nl> + NewArgs . push_back ( CEI . ConcreteValue ) ; <nl> + <nl> + assert ( Apply . getOrigCalleeType ( ) - > isPolymorphic ( ) ) ; <nl> + <nl> + / / Form a new set of substitutions where Self is <nl> + / / replaced by a concrete type . <nl> + SubstitutionMap OrigCallSubs = Apply . getSubstitutionMap ( ) ; <nl> + SubstitutionMap NewCallSubs = OrigCallSubs . subst ( <nl> + [ & ] ( SubstitutableType * type ) - > Type { <nl> + if ( type = = CEI . OpenedArchetype ) <nl> + return CEI . ConcreteType ; <nl> + return type ; <nl> + } , <nl> + [ & ] ( CanType origTy , Type substTy , <nl> + ProtocolDecl * proto ) - > Optional < ProtocolConformanceRef > { <nl> + if ( origTy - > isEqual ( CEI . OpenedArchetype ) ) { <nl> + assert ( substTy - > isEqual ( CEI . ConcreteType ) ) ; <nl> + / / Do a conformance lookup on this witness requirement using the <nl> + / / existential ' s conformances . The witness requirement may be a base <nl> + / / type of the existential ' s requirements . <nl> + return CEI . lookupExistentialConformance ( proto ) . getValue ( ) ; <nl> + } <nl> + return ProtocolConformanceRef ( proto ) ; <nl> + } ) ; <nl> <nl> - / / Now create the new apply instruction . <nl> SILBuilderWithScope ApplyBuilder ( Apply . getInstruction ( ) , BuilderCtx ) ; <nl> FullApplySite NewApply ; <nl> if ( auto * TAI = dyn_cast < TryApplyInst > ( Apply ) ) <nl> SILCombiner : : propagateConcreteTypeOfInitExistential ( FullApplySite Apply , <nl> replaceWitnessMethodInst ( WMI , BuilderCtx , CEI . ConcreteType , <nl> SelfConformance ) ; <nl> } <nl> - / / Construct the map for Self to be used for createApplyWithConcreteType . <nl> - llvm : : SmallDenseMap < unsigned , const ConcreteExistentialInfo * > CEIs ; <nl> - CEIs . insert ( std : : pair < unsigned , const ConcreteExistentialInfo * > ( <nl> - Apply . getCalleeArgIndex ( Apply . getSelfArgumentOperand ( ) ) , & CEI ) ) ; <nl> / / Try to rewrite the apply . <nl> - return createApplyWithConcreteType ( Apply , CEIs , BuilderCtx ) ; <nl> + return createApplyWithConcreteType ( Apply , CEI , BuilderCtx ) ; <nl> } <nl> <nl> / / / Rewrite a protocol extension lookup type from an archetype to a concrete <nl> SILCombiner : : propagateConcreteTypeOfInitExistential ( FullApplySite Apply , <nl> / / / = = > apply % f < C : P > ( % ref ) <nl> SILInstruction * <nl> SILCombiner : : propagateConcreteTypeOfInitExistential ( FullApplySite Apply ) { <nl> - / / This optimization requires a generic argument . <nl> - if ( ! Apply . hasSubstitutions ( ) ) <nl> + / / This optimization requires a generic self argument . <nl> + if ( ! Apply . hasSelfArgument ( ) | | ! Apply . hasSubstitutions ( ) ) <nl> + return nullptr ; <nl> + <nl> + / / Try to derive the concrete type of self and a related conformance from <nl> + / / the found init_existential . <nl> + const ConcreteExistentialInfo CEI ( Apply . getSelfArgumentOperand ( ) ) ; <nl> + if ( ! CEI . isValid ( ) ) <nl> return nullptr ; <nl> <nl> SILBuilderContext BuilderCtx ( Builder . getModule ( ) , Builder . getTrackingList ( ) ) ; <nl> SILOpenedArchetypesTracker OpenedArchetypesTracker ( & Builder . getFunction ( ) ) ; <nl> BuilderCtx . setOpenedArchetypesTracker ( & OpenedArchetypesTracker ) ; <nl> - llvm : : SmallDenseMap < unsigned , const ConcreteExistentialInfo * > CEIs ; <nl> - for ( unsigned ArgIdx = 0 ; ArgIdx < Apply . getNumArguments ( ) ; ArgIdx + + ) { <nl> - auto ArgASTType = Apply . getArgument ( ArgIdx ) - > getType ( ) . getASTType ( ) ; <nl> - if ( ! ArgASTType - > hasArchetype ( ) ) <nl> - continue ; <nl> - const ConcreteExistentialInfo CEI ( Apply . getArgumentOperands ( ) [ ArgIdx ] ) ; <nl> - if ( ! CEI . isValid ( ) ) <nl> - continue ; <nl> - <nl> - CEIs . insert ( <nl> - std : : pair < unsigned , const ConcreteExistentialInfo * > ( ArgIdx , & CEI ) ) ; <nl> - <nl> - if ( CEI . ConcreteType - > isOpenedExistential ( ) ) { <nl> - / / Temporarily record this opened existential def in this local <nl> - / / BuilderContext before rewriting the witness method . <nl> - OpenedArchetypesTracker . addOpenedArchetypeDef ( <nl> - cast < ArchetypeType > ( CEI . ConcreteType ) , CEI . ConcreteTypeDef ) ; <nl> - } <nl> + if ( CEI . ConcreteType - > isOpenedExistential ( ) ) { <nl> + / / Temporarily record this opened existential def in this local <nl> + / / BuilderContext before rewriting the witness method . <nl> + OpenedArchetypesTracker . addOpenedArchetypeDef ( <nl> + cast < ArchetypeType > ( CEI . ConcreteType ) , CEI . ConcreteTypeDef ) ; <nl> } <nl> - / / Bail , if no argument has a concrete existential to propagate . <nl> - if ( CEIs . empty ( ) ) <nl> - return nullptr ; <nl> - return createApplyWithConcreteType ( Apply , CEIs , BuilderCtx ) ; <nl> + / / Perform the transformation by rewriting the apply . <nl> + return createApplyWithConcreteType ( Apply , CEI , BuilderCtx ) ; <nl> } <nl> <nl> / / / \ brief Check that all users of the apply are retain / release ignoring one <nl> deleted file mode 100644 <nl> index 2c05903d04aa . . 000000000000 <nl> mmm a / test / SILOptimizer / sil_combiner_concrete_prop_all_args . sil <nl> ppp / dev / null <nl> <nl> - / / RUN : % target - sil - opt - wmo - assume - parsing - unqualified - ownership - sil - enable - sil - verify - all % s - inline - sil - combine - generic - specializer - allocbox - to - stack - copy - forwarding - lower - aggregate - instrs - mem2reg - devirtualizer - late - inline - dead - arg - signature - opt - dce | % FileCheck % s <nl> - import Builtin <nl> - import Swift <nl> - import SwiftShims <nl> - <nl> - internal protocol SomeProtocol : AnyObject { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - internal class SomeClass : SomeProtocol { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - @ inline ( never ) internal func wrap_foo_cp ( a : SomeProtocol ) - > Int32 <nl> - <nl> - func cp ( ) <nl> - <nl> - internal protocol SomeNoClassProtocol { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - internal class SomeNoClass : SomeNoClassProtocol { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - @ inline ( never ) internal func wrap_foo_ncp ( a : SomeNoClassProtocol ) - > Int32 <nl> - <nl> - @ inline ( never ) func ncp ( ) <nl> - <nl> - internal protocol SomeClassProtocolComp : AnyObject { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - internal protocol SomeOtherClassProtocolComp : AnyObject { <nl> - func bar ( ) - > Int32 <nl> - } <nl> - <nl> - internal class SomeClassComp : SomeClassProtocolComp , SomeOtherClassProtocolComp { <nl> - func foo ( ) - > Int32 <nl> - func bar ( ) - > Int32 <nl> - } <nl> - <nl> - @ inline ( never ) internal func wrap_foo_bar_cpc ( a : SomeClassProtocolComp & SomeOtherClassProtocolComp ) - > Int32 <nl> - <nl> - func cpc ( ) <nl> - <nl> - internal protocol SomeNoClassProtocolComp { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - internal protocol SomeOtherNoClassProtocolComp { <nl> - func bar ( ) - > Int32 <nl> - } <nl> - <nl> - internal class SomeNoClassComp : SomeNoClassProtocolComp , SomeOtherNoClassProtocolComp { <nl> - func foo ( ) - > Int32 <nl> - func bar ( ) - > Int32 <nl> - } <nl> - <nl> - @ inline ( never ) internal func wrap_no_foo_bar_comp_ncpc ( a : SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp ) - > Int32 <nl> - <nl> - @ inline ( never ) func ncpc ( ) <nl> - <nl> - internal protocol P : AnyObject { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - internal class K : P { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - internal class KPrime : P { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - @ inline ( never ) internal func do_not_optimize_cp ( a : P ) - > Int32 <nl> - <nl> - internal protocol PP : AnyObject { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - internal class KK : PP { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - internal class KKPrime : PP { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - @ inline ( never ) internal func wrap_inout_cp ( a : inout PP ) - > Int32 <nl> - <nl> - @ inline ( never ) func do_not_optimize_inout_cp ( ) <nl> - <nl> - internal protocol PPP { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - internal class KKK : PPP { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - @ inline ( never ) internal func wrap_inout_ncp ( a : inout PPP ) - > Int32 <nl> - <nl> - @ inline ( never ) func inout_ncp ( ) <nl> - <nl> - internal protocol PPPP { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - internal struct SSSS : PPPP { <nl> - func foo ( ) - > Int32 <nl> - } <nl> - <nl> - @ inline ( never ) internal func wrap_struct_inout_ncp ( a : inout PPPP ) - > Int32 <nl> - <nl> - @ inline ( never ) func struct_inout_ncp ( ) <nl> - <nl> - <nl> - sil hidden @ $ S21existential_transform9SomeClassC3foos5Int32VyF : $ @ convention ( method ) ( @ guaranteed SomeClass ) - > Int32 { <nl> - bb0 ( % 0 : $ SomeClass ) : <nl> - % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform9SomeClassC3foos5Int32VyF ' <nl> - <nl> - sil private [ transparent ] [ thunk ] @ $ S21existential_transform9SomeClassCAA0C8ProtocolA2aDP3foos5Int32VyFTW : $ @ convention ( witness_method : SomeProtocol ) ( @ guaranteed SomeClass ) - > Int32 { <nl> - bb0 ( % 0 : $ SomeClass ) : <nl> - % 1 = class_method % 0 : $ SomeClass , # SomeClass . foo ! 1 : ( SomeClass ) - > ( ) - > Int32 , $ @ convention ( method ) ( @ guaranteed SomeClass ) - > Int32 <nl> - % 2 = apply % 1 ( % 0 ) : $ @ convention ( method ) ( @ guaranteed SomeClass ) - > Int32 <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform9SomeClassCAA0C8ProtocolA2aDP3foos5Int32VyFTW ' <nl> - <nl> - sil hidden [ signature_optimized_thunk ] [ always_inline ] @ $ S21existential_transform11wrap_foo_cp1as5Int32VAA12SomeProtocol_p_tF : $ @ convention ( thin ) ( @ guaranteed SomeProtocol ) - > Int32 { <nl> - bb0 ( % 0 : $ SomeProtocol ) : <nl> - % 1 = function_ref @ $ S21existential_transform11wrap_foo_cp1as5Int32VAA12SomeProtocol_p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeProtocol > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - % 2 = open_existential_ref % 0 : $ SomeProtocol to $ @ opened ( " CC97E160 - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeProtocol <nl> - % 3 = apply % 1 < @ opened ( " CC97E160 - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeProtocol > ( % 2 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeProtocol > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - return % 3 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform11wrap_foo_cp1as5Int32VAA12SomeProtocol_p_tF ' <nl> - <nl> - / / CHECK - LABEL : sil hidden @ $ S21existential_transform2cpyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - / / CHECK : bb0 : <nl> - / / CHECK : % 0 = alloc_ref $ SomeClass <nl> - / / CHECK : debug_value % 0 : $ SomeClass , let , name " self " , argno 1 <nl> - / / CHECK : % 2 = function_ref @ $ S21existential_transform11wrap_foo_cp1as5Int32VAA12SomeProtocol_p_tFTf4e_n4main0G5ClassC_Tg5 : $ @ convention ( thin ) ( @ guaranteed SomeClass ) - > Int32 <nl> - / / CHECK : % 3 = apply % 2 ( % 0 ) : $ @ convention ( thin ) ( @ guaranteed SomeClass ) - > Int32 <nl> - / / CHECK : strong_release % 0 : $ SomeClass <nl> - / / CHECK : % 5 = tuple ( ) <nl> - / / CHECK : return % 5 : $ ( ) <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform2cpyyF ' <nl> - sil hidden @ $ S21existential_transform2cpyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - bb0 : <nl> - % 0 = alloc_ref $ SomeClass <nl> - debug_value % 0 : $ SomeClass , let , name " self " , argno 1 <nl> - % 2 = init_existential_ref % 0 : $ SomeClass : $ SomeClass , $ SomeProtocol <nl> - debug_value % 2 : $ SomeProtocol , let , name " magic1 " <nl> - % 4 = function_ref @ $ S21existential_transform11wrap_foo_cp1as5Int32VAA12SomeProtocol_p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeProtocol > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - % 5 = open_existential_ref % 2 : $ SomeProtocol to $ @ opened ( " CC97E55C - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeProtocol <nl> - % 6 = apply % 4 < @ opened ( " CC97E55C - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeProtocol > ( % 5 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeProtocol > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - strong_release % 0 : $ SomeClass <nl> - % 8 = tuple ( ) <nl> - return % 8 : $ ( ) <nl> - } / / end sil function ' $ S21existential_transform2cpyyF ' <nl> - <nl> - sil hidden @ $ S21existential_transform11SomeNoClassC3foos5Int32VyF : $ @ convention ( method ) ( @ guaranteed SomeNoClass ) - > Int32 { <nl> - bb0 ( % 0 : $ SomeNoClass ) : <nl> - % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform11SomeNoClassC3foos5Int32VyF ' <nl> - <nl> - sil private [ transparent ] [ thunk ] @ $ S21existential_transform11SomeNoClassCAA0cdE8ProtocolA2aDP3foos5Int32VyFTW : $ @ convention ( witness_method : SomeNoClassProtocol ) ( @ in_guaranteed SomeNoClass ) - > Int32 { <nl> - bb0 ( % 0 : $ * SomeNoClass ) : <nl> - % 1 = load % 0 : $ * SomeNoClass <nl> - % 2 = class_method % 1 : $ SomeNoClass , # SomeNoClass . foo ! 1 : ( SomeNoClass ) - > ( ) - > Int32 , $ @ convention ( method ) ( @ guaranteed SomeNoClass ) - > Int32 <nl> - % 3 = apply % 2 ( % 1 ) : $ @ convention ( method ) ( @ guaranteed SomeNoClass ) - > Int32 <nl> - return % 3 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform11SomeNoClassCAA0cdE8ProtocolA2aDP3foos5Int32VyFTW ' <nl> - <nl> - sil hidden [ signature_optimized_thunk ] [ always_inline ] @ $ S21existential_transform12wrap_foo_ncp1as5Int32VAA19SomeNoClassProtocol_p_tF : $ @ convention ( thin ) ( @ in_guaranteed SomeNoClassProtocol ) - > Int32 { <nl> - bb0 ( % 0 : $ * SomeNoClassProtocol ) : <nl> - % 1 = function_ref @ $ S21existential_transform12wrap_foo_ncp1as5Int32VAA19SomeNoClassProtocol_p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeNoClassProtocol > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - % 2 = open_existential_addr mutable_access % 0 : $ * SomeNoClassProtocol to $ * @ opened ( " CC97FCD6 - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeNoClassProtocol <nl> - % 3 = apply % 1 < @ opened ( " CC97FCD6 - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeNoClassProtocol > ( % 2 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeNoClassProtocol > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - return % 3 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform12wrap_foo_ncp1as5Int32VAA19SomeNoClassProtocol_p_tF ' <nl> - <nl> - / / CHECK - LABEL : sil hidden [ noinline ] @ $ S21existential_transform3ncpyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - / / CHECK : bb0 : <nl> - / / CHECK : % 0 = alloc_ref $ SomeNoClass <nl> - / / CHECK : debug_value % 0 : $ SomeNoClass , let , name " self " , argno 1 <nl> - / / CHECK : % 2 = function_ref @ $ S21existential_transform12wrap_foo_ncp1as5Int32VAA19SomeNoClassProtocol_p_tFTf4e_n4main0ghI0C_Tg5 : $ @ convention ( thin ) ( @ guaranteed SomeNoClass ) - > Int32 <nl> - / / CHECK : % 3 = apply % 2 ( % 0 ) : $ @ convention ( thin ) ( @ guaranteed SomeNoClass ) - > Int32 <nl> - / / CHECK : strong_release % 0 : $ SomeNoClass <nl> - / / CHECK : % 5 = tuple ( ) <nl> - / / CHECK : return % 5 : $ ( ) <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform3ncpyyF ' <nl> - sil hidden [ noinline ] @ $ S21existential_transform3ncpyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - bb0 : <nl> - % 0 = alloc_stack $ SomeNoClassProtocol , let , name " magic2 " <nl> - % 1 = alloc_ref $ SomeNoClass <nl> - debug_value % 1 : $ SomeNoClass , let , name " self " , argno 1 <nl> - % 3 = init_existential_addr % 0 : $ * SomeNoClassProtocol , $ SomeNoClass <nl> - store % 1 to % 3 : $ * SomeNoClass <nl> - % 5 = function_ref @ $ S21existential_transform12wrap_foo_ncp1as5Int32VAA19SomeNoClassProtocol_p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeNoClassProtocol > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - % 6 = open_existential_addr mutable_access % 0 : $ * SomeNoClassProtocol to $ * @ opened ( " CC9800F0 - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeNoClassProtocol <nl> - % 7 = apply % 5 < @ opened ( " CC9800F0 - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeNoClassProtocol > ( % 6 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeNoClassProtocol > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - destroy_addr % 0 : $ * SomeNoClassProtocol <nl> - dealloc_stack % 0 : $ * SomeNoClassProtocol <nl> - % 10 = tuple ( ) <nl> - return % 10 : $ ( ) <nl> - } / / end sil function ' $ S21existential_transform3ncpyyF ' <nl> - <nl> - sil hidden @ $ S21existential_transform13SomeClassCompC3foos5Int32VyF : $ @ convention ( method ) ( @ guaranteed SomeClassComp ) - > Int32 { <nl> - bb0 ( % 0 : $ SomeClassComp ) : <nl> - % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform13SomeClassCompC3foos5Int32VyF ' <nl> - <nl> - sil hidden @ $ S21existential_transform13SomeClassCompC3bars5Int32VyF : $ @ convention ( method ) ( @ guaranteed SomeClassComp ) - > Int32 { <nl> - bb0 ( % 0 : $ SomeClassComp ) : <nl> - % 1 = integer_literal $ Builtin . Int32 , 20 <nl> - % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform13SomeClassCompC3bars5Int32VyF ' <nl> - <nl> - sil private [ transparent ] [ thunk ] @ $ S21existential_transform13SomeClassCompCAA0cd8ProtocolE0A2aDP3foos5Int32VyFTW : $ @ convention ( witness_method : SomeClassProtocolComp ) ( @ guaranteed SomeClassComp ) - > Int32 { <nl> - bb0 ( % 0 : $ SomeClassComp ) : <nl> - % 1 = class_method % 0 : $ SomeClassComp , # SomeClassComp . foo ! 1 : ( SomeClassComp ) - > ( ) - > Int32 , $ @ convention ( method ) ( @ guaranteed SomeClassComp ) - > Int32 <nl> - % 2 = apply % 1 ( % 0 ) : $ @ convention ( method ) ( @ guaranteed SomeClassComp ) - > Int32 <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform13SomeClassCompCAA0cd8ProtocolE0A2aDP3foos5Int32VyFTW ' <nl> - <nl> - sil private [ transparent ] [ thunk ] @ $ S21existential_transform13SomeClassCompCAA0c5Otherd8ProtocolE0A2aDP3bars5Int32VyFTW : $ @ convention ( witness_method : SomeClassProtocolComp ) ( @ guaranteed SomeClassComp ) - > Int32 { <nl> - bb0 ( % 0 : $ SomeClassComp ) : <nl> - % 1 = class_method % 0 : $ SomeClassComp , # SomeClassComp . bar ! 1 : ( SomeClassComp ) - > ( ) - > Int32 , $ @ convention ( method ) ( @ guaranteed SomeClassComp ) - > Int32 <nl> - % 2 = apply % 1 ( % 0 ) : $ @ convention ( method ) ( @ guaranteed SomeClassComp ) - > Int32 <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform13SomeClassCompCAA0c5Otherd8ProtocolE0A2aDP3bars5Int32VyFTW ' <nl> - <nl> - sil hidden [ signature_optimized_thunk ] [ always_inline ] @ $ S21existential_transform16wrap_foo_bar_cpc1as5Int32VAA21SomeClassProtocolComp_AA0h5OtherijK0p_tF : $ @ convention ( thin ) ( @ guaranteed SomeClassProtocolComp & SomeOtherClassProtocolComp ) - > Int32 { <nl> - bb0 ( % 0 : $ SomeClassProtocolComp & SomeOtherClassProtocolComp ) : <nl> - % 1 = function_ref @ $ S21existential_transform16wrap_foo_bar_cpc1as5Int32VAA21SomeClassProtocolComp_AA0h5OtherijK0p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeClassProtocolComp , τ_0_0 : SomeOtherClassProtocolComp > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - % 2 = open_existential_ref % 0 : $ SomeClassProtocolComp & SomeOtherClassProtocolComp to $ @ opened ( " CC981856 - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeClassProtocolComp & SomeOtherClassProtocolComp <nl> - % 3 = apply % 1 < @ opened ( " CC981856 - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeClassProtocolComp & SomeOtherClassProtocolComp > ( % 2 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeClassProtocolComp , τ_0_0 : SomeOtherClassProtocolComp > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - return % 3 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform16wrap_foo_bar_cpc1as5Int32VAA21SomeClassProtocolComp_AA0h5OtherijK0p_tF ' <nl> - <nl> - / / CHECK - LABEL : sil hidden @ $ S21existential_transform3cpcyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - / / CHECK : bb0 : <nl> - / / CHECK : % 0 = alloc_ref $ SomeClassComp <nl> - / / CHECK : debug_value % 0 : $ SomeClassComp , let , name " self " , argno 1 <nl> - / / CHECK : % 2 = function_ref @ $ S21existential_transform16wrap_foo_bar_cpc1as5Int32VAA21SomeClassProtocolComp_AA0h5OtherijK0p_tFTf4e_n4main0hiK0C_Tg5 : $ @ convention ( thin ) ( @ guaranteed SomeClassComp ) - > Int32 <nl> - / / CHECK : % 3 = apply % 2 ( % 0 ) : $ @ convention ( thin ) ( @ guaranteed SomeClassComp ) - > Int32 <nl> - / / CHECK : strong_release % 0 : $ SomeClassComp <nl> - / / CHECK : % 5 = tuple ( ) <nl> - / / CHECK : return % 5 : $ ( ) <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform3cpcyyF ' <nl> - sil hidden @ $ S21existential_transform3cpcyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - bb0 : <nl> - % 0 = alloc_ref $ SomeClassComp <nl> - debug_value % 0 : $ SomeClassComp , let , name " self " , argno 1 <nl> - % 2 = init_existential_ref % 0 : $ SomeClassComp : $ SomeClassComp , $ SomeClassProtocolComp & SomeOtherClassProtocolComp <nl> - debug_value % 2 : $ SomeClassProtocolComp & SomeOtherClassProtocolComp , let , name " magic3 " <nl> - % 4 = function_ref @ $ S21existential_transform16wrap_foo_bar_cpc1as5Int32VAA21SomeClassProtocolComp_AA0h5OtherijK0p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeClassProtocolComp , τ_0_0 : SomeOtherClassProtocolComp > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - % 5 = open_existential_ref % 2 : $ SomeClassProtocolComp & SomeOtherClassProtocolComp to $ @ opened ( " CC981D1A - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeClassProtocolComp & SomeOtherClassProtocolComp <nl> - % 6 = apply % 4 < @ opened ( " CC981D1A - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeClassProtocolComp & SomeOtherClassProtocolComp > ( % 5 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeClassProtocolComp , τ_0_0 : SomeOtherClassProtocolComp > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - strong_release % 0 : $ SomeClassComp <nl> - % 8 = tuple ( ) <nl> - return % 8 : $ ( ) <nl> - } / / end sil function ' $ S21existential_transform3cpcyyF ' <nl> - <nl> - sil hidden @ $ S21existential_transform15SomeNoClassCompC3foos5Int32VyF : $ @ convention ( method ) ( @ guaranteed SomeNoClassComp ) - > Int32 { <nl> - bb0 ( % 0 : $ SomeNoClassComp ) : <nl> - % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform15SomeNoClassCompC3foos5Int32VyF ' <nl> - <nl> - sil hidden @ $ S21existential_transform15SomeNoClassCompC3bars5Int32VyF : $ @ convention ( method ) ( @ guaranteed SomeNoClassComp ) - > Int32 { <nl> - bb0 ( % 0 : $ SomeNoClassComp ) : <nl> - % 1 = integer_literal $ Builtin . Int32 , 20 <nl> - % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform15SomeNoClassCompC3bars5Int32VyF ' <nl> - <nl> - sil private [ transparent ] [ thunk ] @ $ S21existential_transform15SomeNoClassCompCAA0cde8ProtocolF0A2aDP3foos5Int32VyFTW : $ @ convention ( witness_method : SomeNoClassProtocolComp ) ( @ in_guaranteed SomeNoClassComp ) - > Int32 { <nl> - bb0 ( % 0 : $ * SomeNoClassComp ) : <nl> - % 1 = load % 0 : $ * SomeNoClassComp <nl> - % 2 = class_method % 1 : $ SomeNoClassComp , # SomeNoClassComp . foo ! 1 : ( SomeNoClassComp ) - > ( ) - > Int32 , $ @ convention ( method ) ( @ guaranteed SomeNoClassComp ) - > Int32 <nl> - % 3 = apply % 2 ( % 1 ) : $ @ convention ( method ) ( @ guaranteed SomeNoClassComp ) - > Int32 <nl> - return % 3 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform15SomeNoClassCompCAA0cde8ProtocolF0A2aDP3foos5Int32VyFTW ' <nl> - <nl> - sil private [ transparent ] [ thunk ] @ $ S21existential_transform15SomeNoClassCompCAA0c5Otherde8ProtocolF0A2aDP3bars5Int32VyFTW : $ @ convention ( witness_method : SomeNoClassProtocolComp ) ( @ in_guaranteed SomeNoClassComp ) - > Int32 { <nl> - bb0 ( % 0 : $ * SomeNoClassComp ) : <nl> - % 1 = load % 0 : $ * SomeNoClassComp <nl> - % 2 = class_method % 1 : $ SomeNoClassComp , # SomeNoClassComp . bar ! 1 : ( SomeNoClassComp ) - > ( ) - > Int32 , $ @ convention ( method ) ( @ guaranteed SomeNoClassComp ) - > Int32 <nl> - % 3 = apply % 2 ( % 1 ) : $ @ convention ( method ) ( @ guaranteed SomeNoClassComp ) - > Int32 <nl> - return % 3 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform15SomeNoClassCompCAA0c5Otherde8ProtocolF0A2aDP3bars5Int32VyFTW ' <nl> - <nl> - sil hidden [ signature_optimized_thunk ] [ always_inline ] @ $ S21existential_transform25wrap_no_foo_bar_comp_ncpc1as5Int32VAA23SomeNoClassProtocolComp_AA0j5OtherklmN0p_tF : $ @ convention ( thin ) ( @ in_guaranteed SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp ) - > Int32 { <nl> - bb0 ( % 0 : $ * SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp ) : <nl> - % 1 = function_ref @ $ S21existential_transform25wrap_no_foo_bar_comp_ncpc1as5Int32VAA23SomeNoClassProtocolComp_AA0j5OtherklmN0p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeNoClassProtocolComp , τ_0_0 : SomeOtherNoClassProtocolComp > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - % 2 = open_existential_addr mutable_access % 0 : $ * SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp to $ * @ opened ( " CC983642 - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp <nl> - % 3 = apply % 1 < @ opened ( " CC983642 - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp > ( % 2 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeNoClassProtocolComp , τ_0_0 : SomeOtherNoClassProtocolComp > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - return % 3 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform25wrap_no_foo_bar_comp_ncpc1as5Int32VAA23SomeNoClassProtocolComp_AA0j5OtherklmN0p_tF ' <nl> - <nl> - / / CHECK - LABEL : sil hidden [ noinline ] @ $ S21existential_transform4ncpcyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - / / CHECK : bb0 : <nl> - / / CHECK : % 0 = alloc_ref $ SomeNoClassComp <nl> - / / CHECK : debug_value % 0 : $ SomeNoClassComp , let , name " self " , argno 1 <nl> - / / CHECK : % 2 = function_ref @ $ S21existential_transform25wrap_no_foo_bar_comp_ncpc1as5Int32VAA23SomeNoClassProtocolComp_AA0j5OtherklmN0p_tFTf4e_n4main0jklN0C_Tg5 : $ @ convention ( thin ) ( @ guaranteed SomeNoClassComp ) - > Int32 <nl> - / / CHECK : % 3 = apply % 2 ( % 0 ) : $ @ convention ( thin ) ( @ guaranteed SomeNoClassComp ) - > Int32 <nl> - / / CHECK : strong_release % 0 : $ SomeNoClassComp <nl> - / / CHECK : % 5 = tuple ( ) <nl> - / / CHECK : return % 5 : $ ( ) <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform4ncpcyyF ' <nl> - sil hidden [ noinline ] @ $ S21existential_transform4ncpcyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - bb0 : <nl> - % 0 = alloc_stack $ SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp , let , name " magic4 " <nl> - % 1 = alloc_ref $ SomeNoClassComp <nl> - debug_value % 1 : $ SomeNoClassComp , let , name " self " , argno 1 <nl> - % 3 = init_existential_addr % 0 : $ * SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp , $ SomeNoClassComp <nl> - store % 1 to % 3 : $ * SomeNoClassComp <nl> - % 5 = function_ref @ $ S21existential_transform25wrap_no_foo_bar_comp_ncpc1as5Int32VAA23SomeNoClassProtocolComp_AA0j5OtherklmN0p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeNoClassProtocolComp , τ_0_0 : SomeOtherNoClassProtocolComp > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - % 6 = open_existential_addr mutable_access % 0 : $ * SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp to $ * @ opened ( " CC983AFC - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp <nl> - % 7 = apply % 5 < @ opened ( " CC983AFC - AC7C - 11E8 - B742 - D0817AD4059B " ) SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp > ( % 6 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeNoClassProtocolComp , τ_0_0 : SomeOtherNoClassProtocolComp > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - destroy_addr % 0 : $ * SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp <nl> - dealloc_stack % 0 : $ * SomeNoClassProtocolComp & SomeOtherNoClassProtocolComp <nl> - % 10 = tuple ( ) <nl> - return % 10 : $ ( ) <nl> - } / / end sil function ' $ S21existential_transform4ncpcyyF ' <nl> - <nl> - sil hidden @ $ S21existential_transform1KC3foos5Int32VyF : $ @ convention ( method ) ( @ guaranteed K ) - > Int32 { <nl> - bb0 ( % 0 : $ K ) : <nl> - % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform1KC3foos5Int32VyF ' <nl> - <nl> - sil private [ transparent ] [ thunk ] @ $ S21existential_transform1KCAA1PA2aDP3foos5Int32VyFTW : $ @ convention ( witness_method : P ) ( @ guaranteed K ) - > Int32 { <nl> - bb0 ( % 0 : $ K ) : <nl> - % 1 = class_method % 0 : $ K , # K . foo ! 1 : ( K ) - > ( ) - > Int32 , $ @ convention ( method ) ( @ guaranteed K ) - > Int32 <nl> - % 2 = apply % 1 ( % 0 ) : $ @ convention ( method ) ( @ guaranteed K ) - > Int32 <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform1KCAA1PA2aDP3foos5Int32VyFTW ' <nl> - <nl> - / / CHECK - LABEL : sil hidden [ noinline ] @ $ S21existential_transform18do_not_optimize_cp1as5Int32VAA1P_p_tF : $ @ convention ( thin ) ( @ guaranteed P ) - > Int32 { <nl> - / / CHECK : bb0 ( % 0 : $ P ) : <nl> - / / CHECK : debug_value % 0 : $ P , let , name " a " , argno 1 <nl> - / / CHECK : % 2 = open_existential_ref % 0 : $ P to $ @ opened ( " { { . * } } " ) P <nl> - / / CHECK : % 3 = witness_method $ @ opened ( " { { . * } } " ) P , # P . foo ! 1 : < Self where Self : P > ( Self ) - > ( ) - > Int32 , % 2 : $ @ opened ( " { { . * } } " ) P : $ @ convention ( witness_method : P ) < τ_0_0 where τ_0_0 : P > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - / / CHECK : % 4 = apply % 3 < @ opened ( " { { . * } } " ) P > ( % 2 ) : $ @ convention ( witness_method : P ) < τ_0_0 where τ_0_0 : P > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - / / CHECK : return % 4 : $ Int32 <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform18do_not_optimize_cp1as5Int32VAA1P_p_tF ' <nl> - sil hidden [ noinline ] @ $ S21existential_transform18do_not_optimize_cp1as5Int32VAA1P_p_tF : $ @ convention ( thin ) ( @ guaranteed P ) - > Int32 { <nl> - bb0 ( % 0 : $ P ) : <nl> - debug_value % 0 : $ P , let , name " a " , argno 1 <nl> - % 2 = open_existential_ref % 0 : $ P to $ @ opened ( " CC9697D8 - AC7C - 11E8 - B742 - D0817AD4059B " ) P <nl> - % 3 = witness_method $ @ opened ( " CC9697D8 - AC7C - 11E8 - B742 - D0817AD4059B " ) P , # P . foo ! 1 : < Self where Self : P > ( Self ) - > ( ) - > Int32 , % 2 : $ @ opened ( " CC9697D8 - AC7C - 11E8 - B742 - D0817AD4059B " ) P : $ @ convention ( witness_method : P ) < τ_0_0 where τ_0_0 : P > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - % 4 = apply % 3 < @ opened ( " CC9697D8 - AC7C - 11E8 - B742 - D0817AD4059B " ) P > ( % 2 ) : $ @ convention ( witness_method : P ) < τ_0_0 where τ_0_0 : P > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - return % 4 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform18do_not_optimize_cp1as5Int32VAA1P_p_tF ' <nl> - <nl> - sil hidden @ $ S21existential_transform2KKC3foos5Int32VyF : $ @ convention ( method ) ( @ guaranteed KK ) - > Int32 { <nl> - bb0 ( % 0 : $ KK ) : <nl> - % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform2KKC3foos5Int32VyF ' <nl> - <nl> - sil private [ transparent ] [ thunk ] @ $ S21existential_transform2KKCAA2PPA2aDP3foos5Int32VyFTW : $ @ convention ( witness_method : PP ) ( @ guaranteed KK ) - > Int32 { <nl> - bb0 ( % 0 : $ KK ) : <nl> - % 1 = class_method % 0 : $ KK , # KK . foo ! 1 : ( KK ) - > ( ) - > Int32 , $ @ convention ( method ) ( @ guaranteed KK ) - > Int32 <nl> - % 2 = apply % 1 ( % 0 ) : $ @ convention ( method ) ( @ guaranteed KK ) - > Int32 <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform2KKCAA2PPA2aDP3foos5Int32VyFTW ' <nl> - <nl> - <nl> - sil hidden [ noinline ] @ $ S21existential_transform13wrap_inout_cp1as5Int32VAA2PP_pz_tF : $ @ convention ( thin ) ( @ inout PP ) - > Int32 { <nl> - bb0 ( % 0 : $ * PP ) : <nl> - debug_value_addr % 0 : $ * PP , var , name " a " , argno 1 <nl> - % 2 = load % 0 : $ * PP <nl> - % 3 = open_existential_ref % 2 : $ PP to $ @ opened ( " CC969B02 - AC7C - 11E8 - B742 - D0817AD4059B " ) PP <nl> - % 4 = witness_method $ @ opened ( " CC969B02 - AC7C - 11E8 - B742 - D0817AD4059B " ) PP , # PP . foo ! 1 : < Self where Self : PP > ( Self ) - > ( ) - > Int32 , % 3 : $ @ opened ( " CC969B02 - AC7C - 11E8 - B742 - D0817AD4059B " ) PP : $ @ convention ( witness_method : PP ) < τ_0_0 where τ_0_0 : PP > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - strong_retain % 2 : $ PP <nl> - % 6 = apply % 4 < @ opened ( " CC969B02 - AC7C - 11E8 - B742 - D0817AD4059B " ) PP > ( % 3 ) : $ @ convention ( witness_method : PP ) < τ_0_0 where τ_0_0 : PP > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - strong_release % 2 : $ PP <nl> - return % 6 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform13wrap_inout_cp1as5Int32VAA2PP_pz_tF ' <nl> - <nl> - / / CHECK - LABEL : sil hidden [ noinline ] @ $ S21existential_transform24do_not_optimize_inout_cpyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - / / CHECK : bb0 : <nl> - / / CHECK : % 0 = alloc_stack $ PP , var , name " magic5 " <nl> - / / CHECK : % 1 = alloc_ref $ KK <nl> - / / CHECK : debug_value % 1 : $ KK , let , name " self " , argno 1 <nl> - / / CHECK : % 3 = init_existential_ref % 1 : $ KK : $ KK , $ PP <nl> - / / CHECK : store % 3 to % 0 : $ * PP <nl> - / / CHECK : % 5 = function_ref @ $ S21existential_transform13wrap_inout_cp1as5Int32VAA2PP_pz_tF : $ @ convention ( thin ) ( @ inout PP ) - > Int32 <nl> - / / CHECK : % 6 = apply % 5 ( % 0 ) : $ @ convention ( thin ) ( @ inout PP ) - > Int32 <nl> - / / CHECK : % 7 = load % 0 : $ * PP <nl> - / / CHECK : strong_release % 7 : $ PP <nl> - / / CHECK : dealloc_stack % 0 : $ * PP <nl> - / / CHECK : % 10 = tuple ( ) <nl> - / / CHECK : return % 10 : $ ( ) <nl> - / / CHECK : } / / end sil function ' $ S21existential_transform24do_not_optimize_inout_cpyyF ' <nl> - sil hidden [ noinline ] @ $ S21existential_transform24do_not_optimize_inout_cpyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - bb0 : <nl> - % 0 = alloc_stack $ PP , var , name " magic5 " <nl> - % 1 = alloc_ref $ KK <nl> - debug_value % 1 : $ KK , let , name " self " , argno 1 <nl> - % 3 = init_existential_ref % 1 : $ KK : $ KK , $ PP <nl> - store % 3 to % 0 : $ * PP <nl> - % 5 = function_ref @ $ S21existential_transform13wrap_inout_cp1as5Int32VAA2PP_pz_tF : $ @ convention ( thin ) ( @ inout PP ) - > Int32 <nl> - % 6 = apply % 5 ( % 0 ) : $ @ convention ( thin ) ( @ inout PP ) - > Int32 <nl> - % 7 = load % 0 : $ * PP <nl> - strong_release % 7 : $ PP <nl> - dealloc_stack % 0 : $ * PP <nl> - % 10 = tuple ( ) <nl> - return % 10 : $ ( ) <nl> - } / / end sil function ' $ S21existential_transform24do_not_optimize_inout_cpyyF ' <nl> - <nl> - sil hidden @ $ S21existential_transform3KKKC3foos5Int32VyF : $ @ convention ( method ) ( @ guaranteed KKK ) - > Int32 { <nl> - bb0 ( % 0 : $ KKK ) : <nl> - % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform3KKKC3foos5Int32VyF ' <nl> - <nl> - sil private [ transparent ] [ thunk ] @ $ S21existential_transform3KKKCAA3PPPA2aDP3foos5Int32VyFTW : $ @ convention ( witness_method : PPP ) ( @ in_guaranteed KKK ) - > Int32 { <nl> - bb0 ( % 0 : $ * KKK ) : <nl> - % 1 = load % 0 : $ * KKK <nl> - % 2 = class_method % 1 : $ KKK , # KKK . foo ! 1 : ( KKK ) - > ( ) - > Int32 , $ @ convention ( method ) ( @ guaranteed KKK ) - > Int32 <nl> - % 3 = apply % 2 ( % 1 ) : $ @ convention ( method ) ( @ guaranteed KKK ) - > Int32 <nl> - return % 3 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform3KKKCAA3PPPA2aDP3foos5Int32VyFTW ' <nl> - <nl> - sil hidden [ signature_optimized_thunk ] [ always_inline ] @ $ S21existential_transform14wrap_inout_ncp1as5Int32VAA3PPP_pz_tF : $ @ convention ( thin ) ( @ inout PPP ) - > Int32 { <nl> - bb0 ( % 0 : $ * PPP ) : <nl> - % 1 = function_ref @ $ S21existential_transform14wrap_inout_ncp1as5Int32VAA3PPP_pz_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : PPP > ( @ inout τ_0_0 ) - > Int32 <nl> - % 2 = open_existential_addr mutable_access % 0 : $ * PPP to $ * @ opened ( " CC986BDA - AC7C - 11E8 - B742 - D0817AD4059B " ) PPP <nl> - % 3 = apply % 1 < @ opened ( " CC986BDA - AC7C - 11E8 - B742 - D0817AD4059B " ) PPP > ( % 2 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : PPP > ( @ inout τ_0_0 ) - > Int32 <nl> - return % 3 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform14wrap_inout_ncp1as5Int32VAA3PPP_pz_tF ' <nl> - <nl> - / / CHECK - LABEL : sil hidden [ noinline ] @ $ S21existential_transform9inout_ncpyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - / / CHECK : bb0 : <nl> - / / CHECK : % 0 = alloc_stack $ KKK , var , name " magic6 " <nl> - / / CHECK : % 1 = alloc_ref $ KKK <nl> - / / CHECK : debug_value % 1 : $ KKK , let , name " self " , argno 1 <nl> - / / CHECK : store % 1 to % 0 : $ * KKK <nl> - / / CHECK : % 4 = function_ref @ $ S21existential_transform14wrap_inout_ncp1as5Int32VAA3PPP_pz_tFTf4e_n4main3KKKC_Tg5 : $ @ convention ( thin ) ( @ inout KKK ) - > Int32 <nl> - / / CHECK : % 5 = apply % 4 ( % 0 ) : $ @ convention ( thin ) ( @ inout KKK ) - > Int32 <nl> - / / CHECK : % 6 = load % 0 : $ * KKK <nl> - / / CHECK : strong_release % 6 : $ KKK <nl> - / / CHECK : dealloc_stack % 0 : $ * KKK <nl> - / / CHECK : % 9 = tuple ( ) <nl> - / / CHECK : return % 9 : $ ( ) <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform9inout_ncpyyF ' <nl> - sil hidden [ noinline ] @ $ S21existential_transform9inout_ncpyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - bb0 : <nl> - % 0 = alloc_stack $ PPP , var , name " magic6 " <nl> - % 1 = alloc_ref $ KKK <nl> - debug_value % 1 : $ KKK , let , name " self " , argno 1 <nl> - % 3 = init_existential_addr % 0 : $ * PPP , $ KKK <nl> - store % 1 to % 3 : $ * KKK <nl> - % 5 = function_ref @ $ S21existential_transform14wrap_inout_ncp1as5Int32VAA3PPP_pz_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : PPP > ( @ inout τ_0_0 ) - > Int32 <nl> - % 6 = open_existential_addr mutable_access % 0 : $ * PPP to $ * @ opened ( " CC986F86 - AC7C - 11E8 - B742 - D0817AD4059B " ) PPP <nl> - % 7 = apply % 5 < @ opened ( " CC986F86 - AC7C - 11E8 - B742 - D0817AD4059B " ) PPP > ( % 6 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : PPP > ( @ inout τ_0_0 ) - > Int32 <nl> - destroy_addr % 0 : $ * PPP <nl> - dealloc_stack % 0 : $ * PPP <nl> - % 10 = tuple ( ) <nl> - return % 10 : $ ( ) <nl> - } / / end sil function ' $ S21existential_transform9inout_ncpyyF ' <nl> - <nl> - sil hidden @ $ S21existential_transform4SSSSV3foos5Int32VyF : $ @ convention ( method ) ( SSSS ) - > Int32 { <nl> - bb0 ( % 0 : $ SSSS ) : <nl> - % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform4SSSSV3foos5Int32VyF ' <nl> - <nl> - sil private [ transparent ] [ thunk ] @ $ S21existential_transform4SSSSVAA4PPPPA2aDP3foos5Int32VyFTW : $ @ convention ( witness_method : PPPP ) ( @ in_guaranteed SSSS ) - > Int32 { <nl> - bb0 ( % 0 : $ * SSSS ) : <nl> - % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform4SSSSVAA4PPPPA2aDP3foos5Int32VyFTW ' <nl> - <nl> - sil hidden [ signature_optimized_thunk ] [ always_inline ] @ $ S21existential_transform21wrap_struct_inout_ncp1as5Int32VAA4PPPP_pz_tF : $ @ convention ( thin ) ( @ inout PPPP ) - > Int32 { <nl> - bb0 ( % 0 : $ * PPPP ) : <nl> - % 1 = function_ref @ $ S21existential_transform21wrap_struct_inout_ncp1as5Int32VAA4PPPP_pz_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : PPPP > ( @ inout τ_0_0 ) - > Int32 <nl> - % 2 = open_existential_addr mutable_access % 0 : $ * PPPP to $ * @ opened ( " CC98A1E0 - AC7C - 11E8 - B742 - D0817AD4059B " ) PPPP <nl> - % 3 = apply % 1 < @ opened ( " CC98A1E0 - AC7C - 11E8 - B742 - D0817AD4059B " ) PPPP > ( % 2 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : PPPP > ( @ inout τ_0_0 ) - > Int32 <nl> - return % 3 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform21wrap_struct_inout_ncp1as5Int32VAA4PPPP_pz_tF ' <nl> - <nl> - <nl> - / / CHECK - LABEL : sil hidden [ noinline ] @ $ S21existential_transform16struct_inout_ncpyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - / / CHECK : bb0 : <nl> - / / CHECK : % 0 = alloc_stack $ SSSS , var , name " magic7 " <nl> - / / CHECK : % 1 = struct $ SSSS ( ) <nl> - / / CHECK : store % 1 to % 0 : $ * SSSS <nl> - / / CHECK : % 3 = function_ref @ $ S21existential_transform21wrap_struct_inout_ncp1as5Int32VAA4PPPP_pz_tFTf4e_n4main4SSSSV_Tg5 : $ @ convention ( thin ) ( @ inout SSSS ) - > Int32 <nl> - / / CHECK : % 4 = apply % 3 ( % 0 ) : $ @ convention ( thin ) ( @ inout SSSS ) - > Int32 <nl> - / / CHECK : dealloc_stack % 0 : $ * SSSS <nl> - / / CHECK : % 6 = tuple ( ) <nl> - / / CHECK : return % 6 : $ ( ) <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform16struct_inout_ncpyyF ' <nl> - sil hidden [ noinline ] @ $ S21existential_transform16struct_inout_ncpyyF : $ @ convention ( thin ) ( ) - > ( ) { <nl> - bb0 : <nl> - % 0 = alloc_stack $ PPPP , var , name " magic7 " <nl> - % 1 = struct $ SSSS ( ) <nl> - % 2 = init_existential_addr % 0 : $ * PPPP , $ SSSS <nl> - store % 1 to % 2 : $ * SSSS <nl> - % 4 = function_ref @ $ S21existential_transform21wrap_struct_inout_ncp1as5Int32VAA4PPPP_pz_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : PPPP > ( @ inout τ_0_0 ) - > Int32 <nl> - % 5 = open_existential_addr mutable_access % 0 : $ * PPPP to $ * @ opened ( " CC98A5E6 - AC7C - 11E8 - B742 - D0817AD4059B " ) PPPP <nl> - % 6 = apply % 4 < @ opened ( " CC98A5E6 - AC7C - 11E8 - B742 - D0817AD4059B " ) PPPP > ( % 5 ) : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : PPPP > ( @ inout τ_0_0 ) - > Int32 <nl> - destroy_addr % 0 : $ * PPPP <nl> - dealloc_stack % 0 : $ * PPPP <nl> - % 9 = tuple ( ) <nl> - return % 9 : $ ( ) <nl> - } / / end sil function ' $ S21existential_transform16struct_inout_ncpyyF ' <nl> - <nl> - <nl> - / / CHECK - LABEL : sil shared [ noinline ] @ $ S21existential_transform11wrap_foo_cp1as5Int32VAA12SomeProtocol_p_tFTf4e_n4main0G5ClassC_Tg5 : $ @ convention ( thin ) ( @ guaranteed SomeClass ) - > Int32 { <nl> - / / CHECK : bb0 ( % 0 : $ SomeClass ) : <nl> - / / CHECK : % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - / / CHECK : % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - / / CHECK : return % 2 : $ Int32 <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform11wrap_foo_cp1as5Int32VAA12SomeProtocol_p_tFTf4e_n4main0G5ClassC_Tg5 ' <nl> - sil shared [ noinline ] @ $ S21existential_transform11wrap_foo_cp1as5Int32VAA12SomeProtocol_p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeProtocol > ( @ guaranteed τ_0_0 ) - > Int32 { <nl> - bb0 ( % 0 : $ τ_0_0 ) : <nl> - % 1 = witness_method $ τ_0_0 , # SomeProtocol . foo ! 1 : < Self where Self : SomeProtocol > ( Self ) - > ( ) - > Int32 : $ @ convention ( witness_method : SomeProtocol ) < τ_0_0 where τ_0_0 : SomeProtocol > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - % 2 = apply % 1 < τ_0_0 > ( % 0 ) : $ @ convention ( witness_method : SomeProtocol ) < τ_0_0 where τ_0_0 : SomeProtocol > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform11wrap_foo_cp1as5Int32VAA12SomeProtocol_p_tFTf4e_n ' <nl> - <nl> - <nl> - / / CHECK - LABEL : sil shared [ noinline ] @ $ S21existential_transform12wrap_foo_ncp1as5Int32VAA19SomeNoClassProtocol_p_tFTf4e_n4main0ghI0C_Tg5 : $ @ convention ( thin ) ( @ guaranteed SomeNoClass ) - > Int32 { <nl> - / / CHECK : bb0 ( % 0 : $ SomeNoClass ) : <nl> - / / CHECK : % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - / / CHECK : % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - / / CHECK : return % 2 : $ Int32 <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform12wrap_foo_ncp1as5Int32VAA19SomeNoClassProtocol_p_tFTf4e_n4main0ghI0C_Tg5 ' <nl> - sil shared [ noinline ] @ $ S21existential_transform12wrap_foo_ncp1as5Int32VAA19SomeNoClassProtocol_p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeNoClassProtocol > ( @ in_guaranteed τ_0_0 ) - > Int32 { <nl> - bb0 ( % 0 : $ * τ_0_0 ) : <nl> - % 1 = witness_method $ τ_0_0 , # SomeNoClassProtocol . foo ! 1 : < Self where Self : SomeNoClassProtocol > ( Self ) - > ( ) - > Int32 : $ @ convention ( witness_method : SomeNoClassProtocol ) < τ_0_0 where τ_0_0 : SomeNoClassProtocol > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - % 2 = apply % 1 < τ_0_0 > ( % 0 ) : $ @ convention ( witness_method : SomeNoClassProtocol ) < τ_0_0 where τ_0_0 : SomeNoClassProtocol > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - return % 2 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform12wrap_foo_ncp1as5Int32VAA19SomeNoClassProtocol_p_tFTf4e_n ' <nl> - <nl> - / / CHECK - LABEL : sil shared [ noinline ] @ $ S21existential_transform16wrap_foo_bar_cpc1as5Int32VAA21SomeClassProtocolComp_AA0h5OtherijK0p_tFTf4e_n4main0hiK0C_Tg5 : $ @ convention ( thin ) ( @ guaranteed SomeClassComp ) - > Int32 { <nl> - / / CHECK : bb0 ( % 0 : $ SomeClassComp ) : <nl> - / / CHECK : % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - / / CHECK : % 2 = integer_literal $ Builtin . Int32 , 20 <nl> - / / CHECK : % 3 = integer_literal $ Builtin . Int1 , - 1 <nl> - / / CHECK : % 4 = builtin " sadd_with_overflow_Int32 " ( % 1 : $ Builtin . Int32 , % 2 : $ Builtin . Int32 , % 3 : $ Builtin . Int1 ) : $ ( Builtin . Int32 , Builtin . Int1 ) <nl> - / / CHECK : % 5 = tuple_extract % 4 : $ ( Builtin . Int32 , Builtin . Int1 ) , 0 <nl> - / / CHECK : % 6 = tuple_extract % 4 : $ ( Builtin . Int32 , Builtin . Int1 ) , 1 <nl> - / / CHECK : cond_fail % 6 : $ Builtin . Int1 <nl> - / / CHECK : % 8 = struct $ Int32 ( % 5 : $ Builtin . Int32 ) <nl> - / / CHECK : return % 8 : $ Int32 <nl> - / / CHECK : } / / end sil function ' $ S21existential_transform16wrap_foo_bar_cpc1as5Int32VAA21SomeClassProtocolComp_AA0h5OtherijK0p_tFTf4e_n4main0hiK0C_Tg5 ' <nl> - sil shared [ noinline ] @ $ S21existential_transform16wrap_foo_bar_cpc1as5Int32VAA21SomeClassProtocolComp_AA0h5OtherijK0p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeClassProtocolComp , τ_0_0 : SomeOtherClassProtocolComp > ( @ guaranteed τ_0_0 ) - > Int32 { <nl> - bb0 ( % 0 : $ τ_0_0 ) : <nl> - % 1 = witness_method $ τ_0_0 , # SomeClassProtocolComp . foo ! 1 : < Self where Self : SomeClassProtocolComp > ( Self ) - > ( ) - > Int32 : $ @ convention ( witness_method : SomeClassProtocolComp ) < τ_0_0 where τ_0_0 : SomeClassProtocolComp > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - % 2 = apply % 1 < τ_0_0 > ( % 0 ) : $ @ convention ( witness_method : SomeClassProtocolComp ) < τ_0_0 where τ_0_0 : SomeClassProtocolComp > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - % 3 = witness_method $ τ_0_0 , # SomeOtherClassProtocolComp . bar ! 1 : < Self where Self : SomeOtherClassProtocolComp > ( Self ) - > ( ) - > Int32 : $ @ convention ( witness_method : SomeOtherClassProtocolComp ) < τ_0_0 where τ_0_0 : SomeOtherClassProtocolComp > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - % 4 = apply % 3 < τ_0_0 > ( % 0 ) : $ @ convention ( witness_method : SomeOtherClassProtocolComp ) < τ_0_0 where τ_0_0 : SomeOtherClassProtocolComp > ( @ guaranteed τ_0_0 ) - > Int32 <nl> - % 5 = struct_extract % 2 : $ Int32 , # Int32 . _value <nl> - % 6 = struct_extract % 4 : $ Int32 , # Int32 . _value <nl> - % 7 = integer_literal $ Builtin . Int1 , - 1 <nl> - % 8 = builtin " sadd_with_overflow_Int32 " ( % 5 : $ Builtin . Int32 , % 6 : $ Builtin . Int32 , % 7 : $ Builtin . Int1 ) : $ ( Builtin . Int32 , Builtin . Int1 ) <nl> - % 9 = tuple_extract % 8 : $ ( Builtin . Int32 , Builtin . Int1 ) , 0 <nl> - % 10 = tuple_extract % 8 : $ ( Builtin . Int32 , Builtin . Int1 ) , 1 <nl> - cond_fail % 10 : $ Builtin . Int1 <nl> - % 12 = struct $ Int32 ( % 9 : $ Builtin . Int32 ) <nl> - return % 12 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform16wrap_foo_bar_cpc1as5Int32VAA21SomeClassProtocolComp_AA0h5OtherijK0p_tFTf4e_n ' <nl> - <nl> - / / CHECK - LABEL : sil shared [ noinline ] @ $ S21existential_transform25wrap_no_foo_bar_comp_ncpc1as5Int32VAA23SomeNoClassProtocolComp_AA0j5OtherklmN0p_tFTf4e_n4main0jklN0C_Tg5 : $ @ convention ( thin ) ( @ guaranteed SomeNoClassComp ) - > Int32 { <nl> - / / CHECK : bb0 ( % 0 : $ SomeNoClassComp ) : <nl> - / / CHECK : % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - / / CHECK : % 2 = integer_literal $ Builtin . Int32 , 20 <nl> - / / CHECK : % 3 = integer_literal $ Builtin . Int1 , - 1 <nl> - / / CHECK : % 4 = builtin " sadd_with_overflow_Int32 " ( % 1 : $ Builtin . Int32 , % 2 : $ Builtin . Int32 , % 3 : $ Builtin . Int1 ) : $ ( Builtin . Int32 , Builtin . Int1 ) <nl> - / / CHECK : % 5 = tuple_extract % 4 : $ ( Builtin . Int32 , Builtin . Int1 ) , 0 <nl> - / / CHECK : % 6 = tuple_extract % 4 : $ ( Builtin . Int32 , Builtin . Int1 ) , 1 <nl> - / / CHECK : cond_fail % 6 : $ Builtin . Int1 <nl> - / / CHECK : % 8 = struct $ Int32 ( % 5 : $ Builtin . Int32 ) <nl> - / / CHECK : return % 8 : $ Int32 <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform25wrap_no_foo_bar_comp_ncpc1as5Int32VAA23SomeNoClassProtocolComp_AA0j5OtherklmN0p_tFTf4e_n4main0jklN0C_Tg5 ' <nl> - sil shared [ noinline ] @ $ S21existential_transform25wrap_no_foo_bar_comp_ncpc1as5Int32VAA23SomeNoClassProtocolComp_AA0j5OtherklmN0p_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : SomeNoClassProtocolComp , τ_0_0 : SomeOtherNoClassProtocolComp > ( @ in_guaranteed τ_0_0 ) - > Int32 { <nl> - bb0 ( % 0 : $ * τ_0_0 ) : <nl> - % 1 = witness_method $ τ_0_0 , # SomeNoClassProtocolComp . foo ! 1 : < Self where Self : SomeNoClassProtocolComp > ( Self ) - > ( ) - > Int32 : $ @ convention ( witness_method : SomeNoClassProtocolComp ) < τ_0_0 where τ_0_0 : SomeNoClassProtocolComp > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - % 2 = apply % 1 < τ_0_0 > ( % 0 ) : $ @ convention ( witness_method : SomeNoClassProtocolComp ) < τ_0_0 where τ_0_0 : SomeNoClassProtocolComp > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - % 3 = witness_method $ τ_0_0 , # SomeOtherNoClassProtocolComp . bar ! 1 : < Self where Self : SomeOtherNoClassProtocolComp > ( Self ) - > ( ) - > Int32 : $ @ convention ( witness_method : SomeOtherNoClassProtocolComp ) < τ_0_0 where τ_0_0 : SomeOtherNoClassProtocolComp > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - % 4 = apply % 3 < τ_0_0 > ( % 0 ) : $ @ convention ( witness_method : SomeOtherNoClassProtocolComp ) < τ_0_0 where τ_0_0 : SomeOtherNoClassProtocolComp > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - % 5 = struct_extract % 2 : $ Int32 , # Int32 . _value <nl> - % 6 = struct_extract % 4 : $ Int32 , # Int32 . _value <nl> - % 7 = integer_literal $ Builtin . Int1 , - 1 <nl> - % 8 = builtin " sadd_with_overflow_Int32 " ( % 5 : $ Builtin . Int32 , % 6 : $ Builtin . Int32 , % 7 : $ Builtin . Int1 ) : $ ( Builtin . Int32 , Builtin . Int1 ) <nl> - % 9 = tuple_extract % 8 : $ ( Builtin . Int32 , Builtin . Int1 ) , 0 <nl> - % 10 = tuple_extract % 8 : $ ( Builtin . Int32 , Builtin . Int1 ) , 1 <nl> - cond_fail % 10 : $ Builtin . Int1 <nl> - % 12 = struct $ Int32 ( % 9 : $ Builtin . Int32 ) <nl> - return % 12 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform25wrap_no_foo_bar_comp_ncpc1as5Int32VAA23SomeNoClassProtocolComp_AA0j5OtherklmN0p_tFTf4e_n ' <nl> - <nl> - / / CHECK - LABEL : sil shared [ noinline ] @ $ S21existential_transform14wrap_inout_ncp1as5Int32VAA3PPP_pz_tFTf4e_n4main3KKKC_Tg5 : $ @ convention ( thin ) ( @ inout KKK ) - > Int32 { <nl> - / / CHECK : bb0 ( % 0 : $ * KKK ) : <nl> - / / CHECK : % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - / / CHECK : % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - / / CHECK : return % 2 : $ Int32 <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform14wrap_inout_ncp1as5Int32VAA3PPP_pz_tFTf4e_n4main3KKKC_Tg5 ' <nl> - sil shared [ noinline ] @ $ S21existential_transform14wrap_inout_ncp1as5Int32VAA3PPP_pz_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : PPP > ( @ inout τ_0_0 ) - > Int32 { <nl> - bb0 ( % 0 : $ * τ_0_0 ) : <nl> - % 1 = alloc_stack $ τ_0_0 <nl> - copy_addr [ take ] % 0 to [ initialization ] % 1 : $ * τ_0_0 <nl> - % 3 = witness_method $ τ_0_0 , # PPP . foo ! 1 : < Self where Self : PPP > ( Self ) - > ( ) - > Int32 : $ @ convention ( witness_method : PPP ) < τ_0_0 where τ_0_0 : PPP > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - % 4 = apply % 3 < τ_0_0 > ( % 1 ) : $ @ convention ( witness_method : PPP ) < τ_0_0 where τ_0_0 : PPP > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - dealloc_stack % 1 : $ * τ_0_0 <nl> - return % 4 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform14wrap_inout_ncp1as5Int32VAA3PPP_pz_tFTf4e_n ' <nl> - <nl> - / / CHECK - LABEL : sil shared [ noinline ] @ $ S21existential_transform21wrap_struct_inout_ncp1as5Int32VAA4PPPP_pz_tFTf4e_n4main4SSSSV_Tg5 : $ @ convention ( thin ) ( @ inout SSSS ) - > Int32 { <nl> - / / CHECK : bb0 ( % 0 : $ * SSSS ) : <nl> - / / CHECK : % 1 = integer_literal $ Builtin . Int32 , 10 <nl> - / / CHECK : % 2 = struct $ Int32 ( % 1 : $ Builtin . Int32 ) <nl> - / / CHECK : return % 2 : $ Int32 <nl> - / / CHECK - LABEL : } / / end sil function ' $ S21existential_transform21wrap_struct_inout_ncp1as5Int32VAA4PPPP_pz_tFTf4e_n4main4SSSSV_Tg5 ' <nl> - sil shared [ noinline ] @ $ S21existential_transform21wrap_struct_inout_ncp1as5Int32VAA4PPPP_pz_tFTf4e_n : $ @ convention ( thin ) < τ_0_0 where τ_0_0 : PPPP > ( @ inout τ_0_0 ) - > Int32 { <nl> - bb0 ( % 0 : $ * τ_0_0 ) : <nl> - % 1 = alloc_stack $ τ_0_0 <nl> - copy_addr [ take ] % 0 to [ initialization ] % 1 : $ * τ_0_0 <nl> - % 3 = witness_method $ τ_0_0 , # PPPP . foo ! 1 : < Self where Self : PPPP > ( Self ) - > ( ) - > Int32 : $ @ convention ( witness_method : PPPP ) < τ_0_0 where τ_0_0 : PPPP > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - % 4 = apply % 3 < τ_0_0 > ( % 1 ) : $ @ convention ( witness_method : PPPP ) < τ_0_0 where τ_0_0 : PPPP > ( @ in_guaranteed τ_0_0 ) - > Int32 <nl> - dealloc_stack % 1 : $ * τ_0_0 <nl> - return % 4 : $ Int32 <nl> - } / / end sil function ' $ S21existential_transform21wrap_struct_inout_ncp1as5Int32VAA4PPPP_pz_tFTf4e_n ' <nl> - <nl> - sil_vtable SomeClass { <nl> - # SomeClass . foo ! 1 : ( SomeClass ) - > ( ) - > Int32 : @ $ S21existential_transform9SomeClassC3foos5Int32VyF / / SomeClass . foo ( ) <nl> - } <nl> - <nl> - sil_vtable SomeNoClass { <nl> - # SomeNoClass . foo ! 1 : ( SomeNoClass ) - > ( ) - > Int32 : @ $ S21existential_transform11SomeNoClassC3foos5Int32VyF / / SomeNoClass . foo ( ) <nl> - } <nl> - <nl> - sil_vtable SomeClassComp { <nl> - # SomeClassComp . foo ! 1 : ( SomeClassComp ) - > ( ) - > Int32 : @ $ S21existential_transform13SomeClassCompC3foos5Int32VyF / / SomeClassComp . foo ( ) <nl> - # SomeClassComp . bar ! 1 : ( SomeClassComp ) - > ( ) - > Int32 : @ $ S21existential_transform13SomeClassCompC3bars5Int32VyF / / SomeClassComp . bar ( ) <nl> - } <nl> - <nl> - sil_vtable SomeNoClassComp { <nl> - # SomeNoClassComp . foo ! 1 : ( SomeNoClassComp ) - > ( ) - > Int32 : @ $ S21existential_transform15SomeNoClassCompC3foos5Int32VyF / / SomeNoClassComp . foo ( ) <nl> - # SomeNoClassComp . bar ! 1 : ( SomeNoClassComp ) - > ( ) - > Int32 : @ $ S21existential_transform15SomeNoClassCompC3bars5Int32VyF / / SomeNoClassComp . bar ( ) <nl> - } <nl> - <nl> - sil_vtable K { <nl> - # K . foo ! 1 : ( K ) - > ( ) - > Int32 : @ $ S21existential_transform1KC3foos5Int32VyF / / K . foo ( ) <nl> - } <nl> - <nl> - sil_vtable KK { <nl> - # KK . foo ! 1 : ( KK ) - > ( ) - > Int32 : @ $ S21existential_transform2KKC3foos5Int32VyF / / KK . foo ( ) <nl> - } <nl> - <nl> - sil_vtable KKK { <nl> - # KKK . foo ! 1 : ( KKK ) - > ( ) - > Int32 : @ $ S21existential_transform3KKKC3foos5Int32VyF / / KKK . foo ( ) <nl> - } <nl> - <nl> - sil_witness_table hidden SomeClass : SomeProtocol module existential_transform { <nl> - method # SomeProtocol . foo ! 1 : < Self where Self : SomeProtocol > ( Self ) - > ( ) - > Int32 : @ $ S21existential_transform9SomeClassCAA0C8ProtocolA2aDP3foos5Int32VyFTW / / protocol witness for SomeProtocol . foo ( ) in conformance SomeClass <nl> - } <nl> - <nl> - sil_witness_table hidden SomeNoClass : SomeNoClassProtocol module existential_transform { <nl> - method # SomeNoClassProtocol . foo ! 1 : < Self where Self : SomeNoClassProtocol > ( Self ) - > ( ) - > Int32 : @ $ S21existential_transform11SomeNoClassCAA0cdE8ProtocolA2aDP3foos5Int32VyFTW / / protocol witness for SomeNoClassProtocol . foo ( ) in conformance SomeNoClass <nl> - } <nl> - <nl> - sil_witness_table hidden SomeClassComp : SomeClassProtocolComp module existential_transform { <nl> - method # SomeClassProtocolComp . foo ! 1 : < Self where Self : SomeClassProtocolComp > ( Self ) - > ( ) - > Int32 : @ $ S21existential_transform13SomeClassCompCAA0cd8ProtocolE0A2aDP3foos5Int32VyFTW / / protocol witness for SomeClassProtocolComp . foo ( ) in conformance SomeClassComp <nl> - } <nl> - <nl> - sil_witness_table hidden SomeClassComp : SomeOtherClassProtocolComp module existential_transform { <nl> - method # SomeOtherClassProtocolComp . bar ! 1 : < Self where Self : SomeOtherClassProtocolComp > ( Self ) - > ( ) - > Int32 : @ $ S21existential_transform13SomeClassCompCAA0c5Otherd8ProtocolE0A2aDP3bars5Int32VyFTW / / protocol witness for SomeOtherClassProtocolComp . bar ( ) in conformance SomeClassComp <nl> - } <nl> - <nl> - sil_witness_table hidden SomeNoClassComp : SomeNoClassProtocolComp module existential_transform { <nl> - method # SomeNoClassProtocolComp . foo ! 1 : < Self where Self : SomeNoClassProtocolComp > ( Self ) - > ( ) - > Int32 : @ $ S21existential_transform15SomeNoClassCompCAA0cde8ProtocolF0A2aDP3foos5Int32VyFTW / / protocol witness for SomeNoClassProtocolComp . foo ( ) in conformance SomeNoClassComp <nl> - } <nl> - <nl> - sil_witness_table hidden SomeNoClassComp : SomeOtherNoClassProtocolComp module existential_transform { <nl> - method # SomeOtherNoClassProtocolComp . bar ! 1 : < Self where Self : SomeOtherNoClassProtocolComp > ( Self ) - > ( ) - > Int32 : @ $ S21existential_transform15SomeNoClassCompCAA0c5Otherde8ProtocolF0A2aDP3bars5Int32VyFTW / / protocol witness for SomeOtherNoClassProtocolComp . bar ( ) in conformance SomeNoClassComp <nl> - } <nl> - <nl> - sil_witness_table hidden K : P module existential_transform { <nl> - method # P . foo ! 1 : < Self where Self : P > ( Self ) - > ( ) - > Int32 : @ $ S21existential_transform1KCAA1PA2aDP3foos5Int32VyFTW / / protocol witness for P . foo ( ) in conformance K <nl> - } <nl> - <nl> - sil_witness_table hidden KK : PP module existential_transform { <nl> - method # PP . foo ! 1 : < Self where Self : PP > ( Self ) - > ( ) - > Int32 : @ $ S21existential_transform2KKCAA2PPA2aDP3foos5Int32VyFTW / / protocol witness for PP . foo ( ) in conformance KK <nl> - } <nl> - <nl> - sil_witness_table hidden KKK : PPP module existential_transform { <nl> - method # PPP . foo ! 1 : < Self where Self : PPP > ( Self ) - > ( ) - > Int32 : @ $ S21existential_transform3KKKCAA3PPPA2aDP3foos5Int32VyFTW / / protocol witness for PPP . foo ( ) in conformance KKK <nl> - } <nl> - <nl> - sil_witness_table hidden SSSS : PPPP module existential_transform { <nl> - method # PPPP . foo ! 1 : < Self where Self : PPPP > ( Self ) - > ( ) - > Int32 : @ $ S21existential_transform4SSSSVAA4PPPPA2aDP3foos5Int32VyFTW / / protocol witness for PPPP . foo ( ) in conformance SSSS <nl> - } <nl>
Revert " Propagate concrete types of arguments to apply "
apple/swift
bd826644d551182cdd350bc69da2ef830a59b4e7
2018-09-11T15:47:01Z
mmm a / tensorflow / compiler / xla / client / client_library . cc <nl> ppp b / tensorflow / compiler / xla / client / client_library . cc <nl> ClientLibrary : : GetOrCreateCompileOnlyClient ( <nl> return cl ; <nl> } <nl> <nl> + / * static * / void ClientLibrary : : DestroyLocalInstances ( ) { <nl> + ClientLibrary & client_library = Singleton ( ) ; <nl> + tensorflow : : mutex_lock lock ( client_library . service_mutex_ ) ; <nl> + <nl> + client_library . local_instances_ . clear ( ) ; <nl> + client_library . compile_only_instances_ . clear ( ) ; <nl> + } <nl> + <nl> } / / namespace xla <nl> mmm a / tensorflow / compiler / xla / client / client_library . h <nl> ppp b / tensorflow / compiler / xla / client / client_library . h <nl> class ClientLibrary { <nl> static StatusOr < CompileOnlyClient * > GetOrCreateCompileOnlyClient ( <nl> perftools : : gputools : : Platform * platform = nullptr ) ; <nl> <nl> + / / Clears the local instance and compile only instance caches . The client <nl> + / / pointers returned by the previous GetOrCreateLocalClient ( ) or <nl> + / / GetOrCreateCompileOnlyClient ( ) invocations are not valid anymore . <nl> + static void DestroyLocalInstances ( ) ; <nl> + <nl> private : <nl> / / Returns the singleton instance of ClientLibrary . <nl> static ClientLibrary & Singleton ( ) ; <nl> mmm a / tensorflow / compiler / xla / service / BUILD <nl> ppp b / tensorflow / compiler / xla / service / BUILD <nl> cc_test ( <nl> " / / tensorflow / compiler / xla / client : computation_builder " , <nl> " / / tensorflow / compiler / xla / client : local_client " , <nl> " / / tensorflow / compiler / xla / client : padding " , <nl> + " / / tensorflow / compiler / xla / tests : hlo_test_base " , <nl> " / / tensorflow / core : lib " , <nl> " / / tensorflow / core : test_main " , <nl> ] , <nl> mmm a / tensorflow / compiler / xla / service / algebraic_simplifier . cc <nl> ppp b / tensorflow / compiler / xla / service / algebraic_simplifier . cc <nl> StatusOr < bool > AlgebraicSimplifier : : Run ( HloModule * module ) { <nl> / / module , invalidating iteration . <nl> std : : vector < HloComputation * > computations ; <nl> for ( auto & comp : module - > computations ( ) ) { <nl> + if ( comp - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> computations . push_back ( comp . get ( ) ) ; <nl> } <nl> for ( auto & comp : computations ) { <nl> mmm a / tensorflow / compiler / xla / service / batchnorm_rewriter . cc <nl> ppp b / tensorflow / compiler / xla / service / batchnorm_rewriter . cc <nl> StatusOr < bool > BatchNormRewriter : : Run ( HloModule * module ) { <nl> / / module , invalidating iteration . <nl> std : : vector < HloComputation * > computations ; <nl> for ( auto & comp : module - > computations ( ) ) { <nl> + if ( comp - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> computations . push_back ( comp . get ( ) ) ; <nl> } <nl> for ( auto & comp : computations ) { <nl> mmm a / tensorflow / compiler / xla / service / buffer_assignment . cc <nl> ppp b / tensorflow / compiler / xla / service / buffer_assignment . cc <nl> void BufferAssigner : : BuildColocatedBufferSets ( <nl> const TuplePointsToAnalysis & points_to_analysis = <nl> buffer_liveness . points_to_analysis ( ) ; <nl> for ( const HloComputation * computation : module - > MakeComputationPostOrder ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> for ( const HloInstruction * instruction : <nl> computation - > MakeInstructionPostOrder ( ) ) { <nl> const HloOpcode opcode = instruction - > opcode ( ) ; <nl> StatusOr < std : : unique_ptr < BufferAssignment > > BufferAssigner : : CreateAssignment ( <nl> / / their own BufferAllocation . <nl> for ( auto * computation : thread_local_computations ) { <nl> TF_RET_CHECK ( computation ! = module - > entry_computation ( ) ) ; <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> TF_RETURN_IF_ERROR ( AssignBuffersForComputation ( <nl> computation , module - > config ( ) . debug_options ( ) , <nl> / * is_thread_local = * / true , colocated_buffers , colocated_allocations , <nl> mmm a / tensorflow / compiler / xla / service / buffer_liveness . cc <nl> ppp b / tensorflow / compiler / xla / service / buffer_liveness . cc <nl> StatusOr < std : : unique_ptr < BufferLiveness > > BufferLiveness : : Run ( <nl> tensorflow : : Status BufferLiveness : : Analyze ( ) { <nl> TF_ASSIGN_OR_RETURN ( points_to_analysis_ , TuplePointsToAnalysis : : Run ( module_ ) ) ; <nl> for ( auto & computation : module_ - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> / / Gather all instructions whose buffers might alias other instructions into <nl> / / the set aliased_buffers_ . This includes those contained as a tuple <nl> / / element in other instruction ' s output . <nl> mmm a / tensorflow / compiler / xla / service / copy_insertion . cc <nl> ppp b / tensorflow / compiler / xla / service / copy_insertion . cc <nl> StatusOr < bool > CopyInsertion : : Run ( HloModule * module ) { <nl> / / Add copies of computation root instructions , if needed . <nl> FlatMap < const HloComputation * , ShapeTree < bool > > while_body_read_only_indices ; <nl> for ( auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> VLOG ( 2 ) < < " computation " < < computation - > name ( ) ; <nl> InstructionCopier root_copier ( computation - > root_instruction ( ) , <nl> / * copy_users = * / { } ) ; <nl> mmm a / tensorflow / compiler / xla / service / cpu / cpu_compiler . cc <nl> ppp b / tensorflow / compiler / xla / service / cpu / cpu_compiler . cc <nl> StatusOr < std : : unique_ptr < Executable > > CpuCompiler : : Compile ( <nl> new std : : map < HloInstruction * , string > ( ) ) ; <nl> for ( auto embedded_computation : <nl> computation - > MakeEmbeddedComputationsList ( ) ) { <nl> + if ( embedded_computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> auto parallel_computation_iter = <nl> parallel_computations . find ( embedded_computation ) ; <nl> / / All parallel computations are considered to be an entry computation for <nl> StatusOr < std : : unique_ptr < Executable > > CpuCompiler : : Compile ( <nl> <nl> for ( auto embedded_computation : <nl> computation - > MakeEmbeddedComputationsList ( ) ) { <nl> + if ( embedded_computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> TF_RETURN_IF_ERROR ( <nl> ir_emitter <nl> . EmitComputation ( embedded_computation , <nl> CpuCompiler : : CompileAheadOfTime ( std : : vector < std : : unique_ptr < HloModule > > modules , <nl> HloComputation * computation = module - > entry_computation ( ) ; <nl> for ( auto embedded_computation : <nl> computation - > MakeEmbeddedComputationsList ( ) ) { <nl> + if ( embedded_computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> TF_RETURN_IF_ERROR ( <nl> ir_emitter <nl> . EmitComputation ( embedded_computation , <nl> mmm a / tensorflow / compiler / xla / service / cpu / cpu_parallelization_preparation . cc <nl> ppp b / tensorflow / compiler / xla / service / cpu / cpu_parallelization_preparation . cc <nl> StatusOr < bool > ParallelizationPreparation : : Run ( HloModule * module ) { <nl> TF_ASSIGN_OR_RETURN ( auto points_to_analysis , <nl> TuplePointsToAnalysis : : Run ( module ) ) ; <nl> for ( auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> HloInstruction * root = computation - > root_instruction ( ) ; <nl> / / Copy root instruction if it does not define its own top - level buffer . <nl> / / TODO ( b / 32885001 ) Remove these copies ( at least for the unambiguous case ) . <nl> mmm a / tensorflow / compiler / xla / service / gpu / fusion_merger . cc <nl> ppp b / tensorflow / compiler / xla / service / gpu / fusion_merger . cc <nl> Status FusionInstructionMerger : : HandleFusion ( HloInstruction * fusion ) { <nl> StatusOr < bool > FusionMerger : : Run ( HloModule * module ) { <nl> bool changed = false ; <nl> VLOG ( 2 ) < < " FusionMerger for module : " < < module - > name ( ) ; <nl> + std : : vector < HloComputation * > computations ; <nl> for ( auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> + computations . push_back ( computation . get ( ) ) ; <nl> + } <nl> + for ( auto & computation : computations ) { <nl> VLOG ( 1 ) < < " Before running FusionInstructionMerger for computation : " <nl> < < computation - > name ( ) ; <nl> XLA_VLOG_LINES ( 3 , computation - > ToString ( ) ) ; <nl> <nl> - FusionInstructionMerger fusion_merger ( computation . get ( ) ) ; <nl> + FusionInstructionMerger fusion_merger ( computation ) ; <nl> TF_RETURN_IF_ERROR ( fusion_merger . Run ( ) ) ; <nl> changed | = fusion_merger . changed ( ) ; <nl> <nl> mmm a / tensorflow / compiler / xla / service / gpu / hlo_schedule . cc <nl> ppp b / tensorflow / compiler / xla / service / gpu / hlo_schedule . cc <nl> GpuHloOrdering : : GpuHloOrdering ( <nl> / / do that yet since it ' s hard to ensure that the order here is the order used <nl> / / by IrEmitterNested . And mismatched ordering bugs would be hard to find . <nl> for ( auto & computation : module - > computations ( ) ) { <nl> - if ( computation . get ( ) ! = module - > entry_computation ( ) ) { <nl> + if ( computation . get ( ) ! = module - > entry_computation ( ) & & <nl> + ! computation - > IsFusionComputation ( ) ) { <nl> predecessors_ . emplace ( computation . get ( ) , <nl> computation - > ComputeReachability ( ) ) ; <nl> } <nl> mmm a / tensorflow / compiler / xla / service / hlo_constant_folding . cc <nl> ppp b / tensorflow / compiler / xla / service / hlo_constant_folding . cc <nl> StatusOr < bool > HloConstantFolding : : Run ( HloModule * module ) { <nl> bool changed = false ; <nl> <nl> for ( auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> for ( auto instruction : computation - > MakeInstructionPostOrder ( ) ) { <nl> / / Skip dead code . <nl> if ( instruction - > user_count ( ) = = 0 & & <nl> mmm a / tensorflow / compiler / xla / service / hlo_cost_analysis_test . cc <nl> ppp b / tensorflow / compiler / xla / service / hlo_cost_analysis_test . cc <nl> limitations under the License . <nl> # include " tensorflow / compiler / xla / service / user_computation . h " <nl> # include " tensorflow / compiler / xla / service / versioned_computation_handle . h " <nl> # include " tensorflow / compiler / xla / shape_util . h " <nl> + # include " tensorflow / compiler / xla / tests / hlo_test_base . h " <nl> # include " tensorflow / core / platform / logging . h " <nl> <nl> # include " tensorflow / compiler / xla / statusor . h " <nl> TEST_F ( HloCostAnalysisTest , MatmulAndConvolutionCanBeTheSameComputation ) { <nl> EXPECT_EQ ( conv_analysis . flop_count ( ) , matmul_analysis . flop_count ( ) ) ; <nl> } <nl> <nl> - using FusionCostAnalysis = : : testing : : Test ; <nl> + using FusionCostAnalysis = HloTestBase ; <nl> <nl> TEST_F ( FusionCostAnalysis , LoopFusion ) { <nl> / / Do this 4 times with different per - second rates to test the computation of <nl> TEST_F ( FusionCostAnalysis , LoopFusion ) { <nl> / / mul = Mul ( exp , C3 ) <nl> / / sub = Sub ( mul , clamp ) <nl> / / tuple = Tuple ( { sub , sub , mul , C1 } ) <nl> - auto c1 = HloInstruction : : CreateConstant ( Literal : : CreateR2F32Linspace ( <nl> - / * from = * / 0 . 0f , / * to = * / 1 . 0f , / * rows = * / 2 , / * cols = * / 2 ) ) ; <nl> - auto c2 = HloInstruction : : CreateConstant ( Literal : : CreateR2F32Linspace ( <nl> - / * from = * / 1 . 0f , / * to = * / 2 . 0f , / * rows = * / 2 , / * cols = * / 2 ) ) ; <nl> - auto c3 = HloInstruction : : CreateConstant ( Literal : : CreateR2F32Linspace ( <nl> - / * from = * / 2 . 0f , / * to = * / 3 . 0f , / * rows = * / 2 , / * cols = * / 2 ) ) ; <nl> - <nl> - auto add = HloInstruction : : CreateBinary ( r2f32 , HloOpcode : : kAdd , c1 . get ( ) , <nl> - c2 . get ( ) ) ; <nl> - auto clamp = HloInstruction : : CreateTernary ( r2f32 , HloOpcode : : kClamp , <nl> - c2 . get ( ) , add . get ( ) , add . get ( ) ) ; <nl> - auto exp = HloInstruction : : CreateUnary ( r2f32 , HloOpcode : : kExp , add . get ( ) ) ; <nl> - auto mul = HloInstruction : : CreateBinary ( r2f32 , HloOpcode : : kMultiply , <nl> - exp . get ( ) , c3 . get ( ) ) ; <nl> - auto sub = HloInstruction : : CreateBinary ( r2f32 , HloOpcode : : kSubtract , <nl> - mul . get ( ) , clamp . get ( ) ) ; <nl> - auto tuple = HloInstruction : : CreateTuple ( <nl> - { sub . get ( ) , sub . get ( ) , mul . get ( ) , c1 . get ( ) } ) ; <nl> - <nl> - auto fusion = HloInstruction : : CreateFusion ( <nl> - r2f32 , HloInstruction : : FusionKind : : kLoop , tuple . get ( ) ) ; <nl> - fusion - > FuseInstruction ( sub . get ( ) ) ; <nl> - fusion - > FuseInstruction ( mul . get ( ) ) ; <nl> - fusion - > FuseInstruction ( exp . get ( ) ) ; <nl> - fusion - > FuseInstruction ( clamp . get ( ) ) ; <nl> - fusion - > FuseInstruction ( add . get ( ) ) ; <nl> + HloComputation : : Builder builder ( TestName ( ) ) ; <nl> + auto c1 = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR2F32Linspace ( <nl> + / * from = * / 0 . 0f , / * to = * / 1 . 0f , / * rows = * / 2 , / * cols = * / 2 ) ) ) ; <nl> + auto c2 = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR2F32Linspace ( <nl> + / * from = * / 1 . 0f , / * to = * / 2 . 0f , / * rows = * / 2 , / * cols = * / 2 ) ) ) ; <nl> + auto c3 = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR2F32Linspace ( <nl> + / * from = * / 2 . 0f , / * to = * / 3 . 0f , / * rows = * / 2 , / * cols = * / 2 ) ) ) ; <nl> + auto add = builder . AddInstruction ( <nl> + HloInstruction : : CreateBinary ( r2f32 , HloOpcode : : kAdd , c1 , c2 ) ) ; <nl> + auto clamp = builder . AddInstruction ( <nl> + HloInstruction : : CreateTernary ( r2f32 , HloOpcode : : kClamp , c2 , add , add ) ) ; <nl> + auto exp = builder . AddInstruction ( <nl> + HloInstruction : : CreateUnary ( r2f32 , HloOpcode : : kExp , add ) ) ; <nl> + auto mul = builder . AddInstruction ( <nl> + HloInstruction : : CreateBinary ( r2f32 , HloOpcode : : kMultiply , exp , c3 ) ) ; <nl> + auto sub = builder . AddInstruction ( <nl> + HloInstruction : : CreateBinary ( r2f32 , HloOpcode : : kSubtract , mul , clamp ) ) ; <nl> + auto tuple = HloInstruction : : CreateTuple ( { sub , sub , mul , c1 } ) ; <nl> + <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto * computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> + auto * fusion = computation - > CreateFusionInstruction ( <nl> + { sub , mul , exp , clamp , add } , HloInstruction : : FusionKind : : kLoop ) ; <nl> <nl> / / The time given these rates at i = = 0 is exactly even among the properties <nl> / / at 1 . 0 seconds . For other values , one of the rates is slower so that it <nl> TEST_F ( FusionCostAnalysis , NoLayout ) { <nl> Shape shape_without_layout = shape_with_layout ; <nl> shape_without_layout . clear_layout ( ) ; <nl> <nl> - auto c1 = HloInstruction : : CreateConstant ( <nl> - Literal : : CreateR4FromArray4D ( Array4D < float > ( 2 , 3 , 4 , 5 ) ) ) ; <nl> - auto c2 = HloInstruction : : CreateConstant ( Literal : : CreateR1 < float > ( { 1 , 2 , 3 } ) ) ; <nl> - <nl> - auto broadcast = <nl> - HloInstruction : : CreateBroadcast ( shape_without_layout , c2 . get ( ) , { 1 } ) ; <nl> - auto add = HloInstruction : : CreateBinary ( shape_with_layout , HloOpcode : : kAdd , <nl> - c1 . get ( ) , broadcast . get ( ) ) ; <nl> - <nl> - auto fusion = HloInstruction : : CreateFusion ( <nl> - shape_with_layout , HloInstruction : : FusionKind : : kLoop , add . get ( ) ) ; <nl> - fusion - > FuseInstruction ( broadcast . get ( ) ) ; <nl> + HloComputation : : Builder builder ( TestName ( ) ) ; <nl> + auto c1 = builder . AddInstruction ( HloInstruction : : CreateConstant ( <nl> + Literal : : CreateR4FromArray4D ( Array4D < float > ( 2 , 3 , 4 , 5 ) ) ) ) ; <nl> + auto c2 = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR1 < float > ( { 1 , 2 , 3 } ) ) ) ; <nl> + <nl> + auto broadcast = builder . AddInstruction ( <nl> + HloInstruction : : CreateBroadcast ( shape_without_layout , c2 , { 1 } ) ) ; <nl> + auto add = builder . AddInstruction ( HloInstruction : : CreateBinary ( <nl> + shape_with_layout , HloOpcode : : kAdd , c1 , broadcast ) ) ; <nl> + <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto * computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> + auto * fusion = computation - > CreateFusionInstruction ( <nl> + { add , broadcast } , HloInstruction : : FusionKind : : kLoop ) ; <nl> <nl> HloCostAnalysis fusion_analysis ( ShapeSize ) ; <nl> ASSERT_IS_OK ( fusion - > Accept ( & fusion_analysis ) ) ; <nl> mmm a / tensorflow / compiler / xla / service / hlo_cse . cc <nl> ppp b / tensorflow / compiler / xla / service / hlo_cse . cc <nl> bool CombineConstants ( HloComputation * computation , bool is_layout_sensitive ) { <nl> StatusOr < bool > HloCSE : : Run ( HloModule * module ) { <nl> bool changed = false ; <nl> for ( auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> changed | = CombineConstants ( computation . get ( ) , is_layout_sensitive_ ) ; <nl> <nl> std : : list < HloInstruction * > post_order = <nl> mmm a / tensorflow / compiler / xla / service / hlo_dce . cc <nl> ppp b / tensorflow / compiler / xla / service / hlo_dce . cc <nl> StatusOr < bool > HloDCE : : Run ( HloModule * module ) { <nl> bool changed = false ; <nl> <nl> for ( auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> std : : unordered_set < HloInstruction * > live_instructions ; <nl> TF_RETURN_IF_ERROR ( computation - > root_instruction ( ) - > Accept ( <nl> [ & live_instructions ] ( HloInstruction * instruction ) { <nl> mmm a / tensorflow / compiler / xla / service / hlo_instruction . cc <nl> ppp b / tensorflow / compiler / xla / service / hlo_instruction . cc <nl> HloInstruction * HloInstruction : : CloneAndFuseInternal ( <nl> HloInstruction * instruction_to_fuse ) { <nl> CHECK_EQ ( opcode_ , HloOpcode : : kFusion ) ; <nl> CHECK ( instruction_to_fuse - > IsFusable ( ) ) ; <nl> - <nl> + if ( GetModule ( ) ) { <nl> + XLA_VLOG_LINES ( 1 , GetModule ( ) - > ToString ( ) ) ; <nl> + } <nl> HloInstruction * clone = nullptr ; <nl> - if ( fused_instructions_computation_ = = nullptr ) { <nl> + if ( called_computations_ . empty ( ) ) { <nl> / / New fusion instruction . <nl> auto builder = HloComputation : : Builder ( " fused_computation " , true ) ; <nl> builder . AddInstruction ( instruction_to_fuse - > Clone ( / * suffix = * / " " ) ) ; <nl> - fused_instructions_computation_ = builder . Build ( ) ; <nl> + called_computations_ . push_back ( <nl> + CHECK_NOTNULL ( GetModule ( ) ) - > AddEmbeddedComputation ( builder . Build ( ) ) ) ; <nl> clone = fused_expression_root ( ) ; <nl> clone - > parent_fusion_instruction_ = this ; <nl> } else { <nl> - CHECK ( fused_instructions_computation_ ! = nullptr & & <nl> - fused_instructions_computation_ - > IsFusionComputation ( ) ) ; <nl> - clone = fused_instructions_computation_ - > AddInstruction ( <nl> + clone = fused_instructions_computation ( ) - > AddInstruction ( <nl> instruction_to_fuse - > Clone ( / * suffix = * / " " ) ) ; <nl> clone - > parent_fusion_instruction_ = this ; <nl> / / instruction_to_fuse is necessarily an operand of the fusion instruction . <nl> HloInstruction * HloInstruction : : CloneAndFuseInternal ( <nl> CHECK ( std : : find ( operands_ . begin ( ) , operands_ . end ( ) , instruction_to_fuse ) ! = <nl> operands_ . end ( ) ) ; <nl> const std : : vector < HloInstruction * > & fused_parameters_ = <nl> - fused_instructions_computation_ - > parameter_instructions ( ) ; <nl> + fused_instructions_computation ( ) - > parameter_instructions ( ) ; <nl> for ( int64 operand_num = 0 ; operand_num < operand_count ( ) ; + + operand_num ) { <nl> if ( instruction_to_fuse = = operands_ [ operand_num ] ) { <nl> / / replace the fused parameter instruction ' s uses with the clone . <nl> HloInstruction * HloInstruction : : CloneAndFuseInternal ( <nl> / / Remove the corresponding fused parameter and operand from their <nl> / / respective vectors . <nl> TF_CHECK_OK ( <nl> - fused_instructions_computation_ - > RemoveParameter ( operand_num ) ) ; <nl> + fused_instructions_computation ( ) - > RemoveParameter ( operand_num ) ) ; <nl> operands_ . erase ( operands_ . begin ( ) + operand_num ) ; <nl> break ; <nl> } <nl> HloInstruction * HloInstruction : : CloneAndFuseInternal ( <nl> <nl> / / Reread the parameters in the computation . <nl> const std : : vector < HloInstruction * > & fused_parameters_ = <nl> - fused_instructions_computation_ - > parameter_instructions ( ) ; <nl> + fused_instructions_computation ( ) - > parameter_instructions ( ) ; <nl> <nl> / / Add each operand of the clone as an operand of the fusion instruction . A <nl> / / complication is that some clone operands may already be operands of the <nl> HloInstruction * HloInstruction : : CloneAndFuseInternal ( <nl> CreateParameter ( param_no , operand - > shape ( ) , param_name ) ; <nl> <nl> param_instruction - > parent_fusion_instruction_ = this ; <nl> - fused_param = fused_instructions_computation_ - > AddParameter ( <nl> + fused_param = fused_instructions_computation ( ) - > AddParameter ( <nl> std : : move ( param_instruction ) ) ; <nl> AppendOperand ( operand ) ; <nl> } <nl> HloInstruction * HloInstruction : : CloneAndFuseInternal ( <nl> called_computations_ . push_back ( computation ) ; <nl> } <nl> } <nl> - <nl> return clone ; <nl> } <nl> <nl> RandomDistribution HloInstruction : : random_distribution ( ) const { <nl> <nl> void HloInstruction : : CheckFusionInstruction ( ) const { <nl> CHECK_EQ ( opcode_ , HloOpcode : : kFusion ) ; <nl> - CHECK ( fused_instructions_computation_ ! = nullptr & & <nl> - fused_instructions_computation_ - > IsFusionComputation ( ) ) ; <nl> <nl> const std : : list < std : : unique_ptr < HloInstruction > > & fused_instructions_ = <nl> - fused_instructions_computation_ - > instructions ( ) ; <nl> + fused_instructions_computation ( ) - > instructions ( ) ; <nl> / / All instructions owned by this fusion instruction must be fused , and the <nl> / / parent fusion instruction of the fused instructions must be ' this ' . <nl> for ( auto & instruction : fused_instructions_ ) { <nl> CHECK ( instruction - > IsFused ( ) ) ; <nl> CHECK_EQ ( this , instruction - > fusion_instruction ( ) ) ; <nl> - CHECK_EQ ( fused_instructions_computation_ . get ( ) , instruction - > parent ( ) ) <nl> + CHECK_EQ ( fused_instructions_computation ( ) , instruction - > parent ( ) ) <nl> < < instruction - > ToString ( ) ; <nl> } <nl> <nl> std : : unique_ptr < HloInstruction > HloInstruction : : CloneFusionWithNewOperands ( <nl> const Shape & shape , tensorflow : : gtl : : ArraySlice < HloInstruction * > operands ) { <nl> CHECK_EQ ( opcode_ , HloOpcode : : kFusion ) ; <nl> CHECK ( parent ( ) ! = nullptr ) ; <nl> - CHECK ( fused_instructions_computation_ ! = nullptr & & <nl> - fused_instructions_computation_ - > IsFusionComputation ( ) ) ; <nl> <nl> auto new_instruction = <nl> WrapUnique ( new HloInstruction ( HloOpcode : : kFusion , shape ) ) ; <nl> std : : unique_ptr < HloInstruction > HloInstruction : : CloneFusionWithNewOperands ( <nl> / / fused instructions . <nl> std : : vector < HloInstruction * > new_fused_parameters ; <nl> const std : : vector < HloInstruction * > & fused_parameters_ = <nl> - fused_instructions_computation_ - > parameter_instructions ( ) ; <nl> + fused_instructions_computation ( ) - > parameter_instructions ( ) ; <nl> const std : : list < std : : unique_ptr < HloInstruction > > & fused_instructions_ = <nl> - fused_instructions_computation_ - > instructions ( ) ; <nl> + fused_instructions_computation ( ) - > instructions ( ) ; <nl> <nl> for ( HloInstruction * old_fused_parameter : fused_parameters_ ) { <nl> new_fused_instructions . push_back ( old_fused_parameter - > Clone ( ) ) ; <nl> std : : unique_ptr < HloInstruction > HloInstruction : : CloneFusionWithNewOperands ( <nl> } <nl> new_instruction - > fusion_kind_ = fusion_kind_ ; <nl> auto computation_builder = HloComputation : : Builder ( <nl> - fused_instructions_computation_ - > name ( ) + " . clone " , true ) ; <nl> + fused_instructions_computation ( ) - > name ( ) + " . clone " , true ) ; <nl> / / We iterated the fusion instructions in reverse post order which means <nl> / / that we must reverse our new list of fusion instructions . <nl> for ( auto new_fused_instruction_iter = new_fused_instructions . rbegin ( ) ; <nl> std : : unique_ptr < HloInstruction > HloInstruction : : CloneFusionWithNewOperands ( <nl> computation_builder . AddInstruction ( std : : move ( * new_fused_instruction_iter ) ) ; <nl> } <nl> auto fused_root_ = fused_expression_root ( ) ; <nl> - new_instruction - > fused_instructions_computation_ = <nl> - computation_builder . Build ( FindOrDie ( old_to_new , fused_root_ ) ) ; <nl> + new_instruction - > called_computations_ . push_back ( <nl> + CHECK_NOTNULL ( GetModule ( ) ) <nl> + - > AddEmbeddedComputation ( <nl> + computation_builder . Build ( FindOrDie ( old_to_new , fused_root_ ) ) ) ) ; <nl> new_instruction - > set_parent ( parent ( ) ) ; <nl> new_instruction - > CheckFusionInstruction ( ) ; <nl> return new_instruction ; <nl> bool HloInstruction : : IsFusable ( ) const { <nl> <nl> HloComputation * HloInstruction : : fused_instructions_computation ( ) const { <nl> CHECK_EQ ( opcode_ , HloOpcode : : kFusion ) ; <nl> - return fused_instructions_computation_ . get ( ) ; <nl> + CHECK ( ! called_computations_ . empty ( ) ) ; <nl> + auto * fused_instructions_computation = called_computations_ . front ( ) ; <nl> + CHECK ( fused_instructions_computation - > IsFusionComputation ( ) ) ; <nl> + return fused_instructions_computation ; <nl> } <nl> <nl> HloInstruction * HloInstruction : : fusion_instruction ( ) const { <nl> HloInstruction * HloInstruction : : fusion_instruction ( ) const { <nl> <nl> HloInstruction * HloInstruction : : fused_expression_root ( ) const { <nl> CHECK_EQ ( opcode_ , HloOpcode : : kFusion ) ; <nl> - CHECK ( fused_instructions_computation_ ! = nullptr & & <nl> - fused_instructions_computation_ - > IsFusionComputation ( ) ) ; <nl> - return fused_instructions_computation_ - > root_instruction ( ) ; <nl> + return fused_instructions_computation ( ) - > root_instruction ( ) ; <nl> } <nl> <nl> HloInstruction * HloInstruction : : fused_parameter ( int64 parameter_number ) const { <nl> CHECK_EQ ( opcode_ , HloOpcode : : kFusion ) ; <nl> - CHECK ( fused_instructions_computation_ ! = nullptr & & <nl> - fused_instructions_computation_ - > IsFusionComputation ( ) ) ; <nl> - return fused_instructions_computation_ - > parameter_instruction ( <nl> + return fused_instructions_computation ( ) - > parameter_instruction ( <nl> parameter_number ) ; <nl> } <nl> <nl> const std : : vector < HloInstruction * > & HloInstruction : : fused_parameters ( ) const { <nl> CHECK_EQ ( opcode_ , HloOpcode : : kFusion ) ; <nl> - CHECK ( fused_instructions_computation_ ! = nullptr & & <nl> - fused_instructions_computation_ - > IsFusionComputation ( ) ) ; <nl> - return fused_instructions_computation_ - > parameter_instructions ( ) ; <nl> + return fused_instructions_computation ( ) - > parameter_instructions ( ) ; <nl> } <nl> <nl> const std : : list < std : : unique_ptr < HloInstruction > > & <nl> HloInstruction : : fused_instructions ( ) const { <nl> CHECK_EQ ( opcode_ , HloOpcode : : kFusion ) ; <nl> - CHECK ( fused_instructions_computation_ ! = nullptr & & <nl> - fused_instructions_computation_ - > IsFusionComputation ( ) ) ; <nl> - return fused_instructions_computation_ - > instructions ( ) ; <nl> + return fused_instructions_computation ( ) - > instructions ( ) ; <nl> } <nl> <nl> HloInstruction : : HloInstruction ( HloOpcode opcode , const Shape & shape ) <nl> static Status PostOrderDFS ( HloInstruction * root , DfsHloVisitor * visitor , <nl> <nl> Status HloInstruction : : Accept ( DfsHloVisitor * visitor , bool call_finish_visit , <nl> bool ignore_control_predecessors ) { <nl> - VLOG ( 2 ) < < " HloInstruction : : Accept ( " < < name ( ) < < " ) " ; <nl> + VLOG ( 3 ) < < " HloInstruction : : Accept ( " < < name ( ) < < " ) " ; <nl> TF_RETURN_IF_ERROR ( <nl> PostOrderDFS ( this , visitor , nullptr , ignore_control_predecessors ) ) ; <nl> if ( call_finish_visit ) { <nl> Status HloInstruction : : AcceptWithOperandOrder ( <nl> TF_RETURN_IF_ERROR ( PostOrderDFS ( this , visitor , & operand_order , <nl> / * ignore_control_predecessors = * / false ) ) ; <nl> if ( call_finish_visit ) { <nl> + VLOG ( 3 ) < < " HloInstruction : : AcceptWithOperandOrder BEFORE FINISH VISIT " ; <nl> TF_RETURN_IF_ERROR ( visitor - > FinishVisit ( this ) ) ; <nl> + VLOG ( 3 ) < < " HloInstruction : : AcceptWithOperandOrder AFTER FINISH VISIT " ; <nl> } <nl> + VLOG ( 2 ) < < " HloInstruction : : AcceptWithOperandOrder EXIT " ; <nl> return Status : : OK ( ) ; <nl> } <nl> <nl> HloModule * HloInstruction : : GetModule ( ) const { <nl> } <nl> <nl> void HloInstruction : : UniquifyName ( NameUniquer * name_uniquer ) { <nl> + string parent_str = parent ( ) = = nullptr ? " noparent " : parent ( ) - > name ( ) ; <nl> name_ = name_uniquer - > GetUniqueName ( name_ ) ; <nl> } <nl> <nl> mmm a / tensorflow / compiler / xla / service / hlo_instruction . h <nl> ppp b / tensorflow / compiler / xla / service / hlo_instruction . h <nl> class HloInstruction { <nl> / / padding of this pad instruction . Only set for pad instructions . <nl> std : : unique_ptr < PaddingConfig > padding_config_ ; <nl> <nl> - / / The computation that stores of instructions fused into this fusion <nl> - / / instruction . Only set for fusion instructions . <nl> - std : : unique_ptr < HloComputation > fused_instructions_computation_ ; <nl> - <nl> / / If this instruction is fused into a fusion instruction , this field points <nl> / / to the fusion instruction . <nl> HloInstruction * parent_fusion_instruction_ = nullptr ; <nl> mmm a / tensorflow / compiler / xla / service / hlo_instruction_test . cc <nl> ppp b / tensorflow / compiler / xla / service / hlo_instruction_test . cc <nl> TEST_F ( HloInstructionTest , PostProcessAllVisitedNodes ) { <nl> } <nl> <nl> TEST_F ( HloInstructionTest , SingletonFusionOp ) { <nl> + HloComputation : : Builder builder ( TestName ( ) ) ; <nl> / / Create a fusion instruction containing a single unary operation . <nl> - auto constant = <nl> - HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ; <nl> - auto exp = <nl> - HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , constant . get ( ) ) ; <nl> - <nl> - auto fusion = HloInstruction : : CreateFusion ( <nl> - r0f32_ , HloInstruction : : FusionKind : : kLoop , exp . get ( ) ) ; <nl> - <nl> - EXPECT_THAT ( fusion - > operands ( ) , ElementsAre ( constant . get ( ) ) ) ; <nl> - EXPECT_THAT ( constant - > users ( ) , UnorderedElementsAre ( fusion . get ( ) , exp . get ( ) ) ) ; <nl> + auto constant = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ) ; <nl> + auto exp = builder . AddInstruction ( <nl> + HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , constant ) ) ; <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto * computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> + auto * fusion = computation - > CreateFusionInstruction ( <nl> + { exp } , HloInstruction : : FusionKind : : kLoop ) ; <nl> + <nl> + EXPECT_THAT ( fusion - > operands ( ) , ElementsAre ( constant ) ) ; <nl> + EXPECT_THAT ( constant - > users ( ) , ElementsAre ( fusion ) ) ; <nl> } <nl> <nl> TEST_F ( HloInstructionTest , BinaryFusionOp ) { <nl> + HloComputation : : Builder builder ( TestName ( ) ) ; <nl> / / Create a fusion instruction containing a single binary operation . <nl> - auto constant1 = <nl> - HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ; <nl> - auto constant2 = <nl> - HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 42 . 1f ) ) ; <nl> - auto add = HloInstruction : : CreateBinary ( r0f32_ , HloOpcode : : kAdd , <nl> - constant1 . get ( ) , constant2 . get ( ) ) ; <nl> - <nl> - auto fusion = HloInstruction : : CreateFusion ( <nl> - r0f32_ , HloInstruction : : FusionKind : : kLoop , add . get ( ) ) ; <nl> - <nl> - EXPECT_THAT ( fusion - > operands ( ) , <nl> - ElementsAre ( constant1 . get ( ) , constant2 . get ( ) ) ) ; <nl> - EXPECT_THAT ( constant1 - > users ( ) , <nl> - UnorderedElementsAre ( fusion . get ( ) , add . get ( ) ) ) ; <nl> - EXPECT_THAT ( constant2 - > users ( ) , <nl> - UnorderedElementsAre ( fusion . get ( ) , add . get ( ) ) ) ; <nl> + auto constant1 = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ) ; <nl> + auto constant2 = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 42 . 1f ) ) ) ; <nl> + auto add = builder . AddInstruction ( HloInstruction : : CreateBinary ( <nl> + r0f32_ , HloOpcode : : kAdd , constant1 , constant2 ) ) ; <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto * computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> + auto * fusion = computation - > CreateFusionInstruction ( <nl> + { add } , HloInstruction : : FusionKind : : kLoop ) ; <nl> + <nl> + EXPECT_THAT ( fusion - > operands ( ) , ElementsAre ( constant1 , constant2 ) ) ; <nl> + EXPECT_THAT ( constant1 - > users ( ) , ElementsAre ( fusion ) ) ; <nl> + EXPECT_THAT ( constant2 - > users ( ) , ElementsAre ( fusion ) ) ; <nl> } <nl> <nl> TEST_F ( HloInstructionTest , ChainFusionOp ) { <nl> + HloComputation : : Builder builder ( TestName ( ) ) ; <nl> / / Create a chain of fused unary ops . <nl> - auto constant = <nl> - HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ; <nl> - auto exp1 = <nl> - HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , constant . get ( ) ) ; <nl> - auto exp2 = HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , exp1 . get ( ) ) ; <nl> - auto exp3 = HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , exp2 . get ( ) ) ; <nl> - <nl> - auto fusion = HloInstruction : : CreateFusion ( <nl> - r0f32_ , HloInstruction : : FusionKind : : kLoop , exp3 . get ( ) ) ; <nl> - fusion - > FuseInstruction ( exp2 . get ( ) ) ; <nl> - fusion - > FuseInstruction ( exp1 . get ( ) ) ; <nl> - <nl> - EXPECT_THAT ( fusion - > operands ( ) , ElementsAre ( constant . get ( ) ) ) ; <nl> - EXPECT_THAT ( constant - > users ( ) , <nl> - UnorderedElementsAre ( fusion . get ( ) , exp1 . get ( ) ) ) ; <nl> + auto constant = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ) ; <nl> + auto exp1 = builder . AddInstruction ( <nl> + HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , constant ) ) ; <nl> + auto exp2 = builder . AddInstruction ( <nl> + HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , exp1 ) ) ; <nl> + auto exp3 = builder . AddInstruction ( <nl> + HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , exp2 ) ) ; <nl> + <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto * computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> + auto * fusion = computation - > CreateFusionInstruction ( <nl> + { exp3 , exp2 , exp1 } , HloInstruction : : FusionKind : : kLoop ) ; <nl> + <nl> + EXPECT_THAT ( fusion - > operands ( ) , ElementsAre ( constant ) ) ; <nl> + EXPECT_THAT ( constant - > users ( ) , ElementsAre ( fusion ) ) ; <nl> } <nl> <nl> TEST_F ( HloInstructionTest , PreserveMetadataInFusionAndClone ) { <nl> + HloComputation : : Builder builder ( TestName ( ) ) ; <nl> / / Create a chain of fused unary ops . <nl> - auto constant = <nl> - HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ; <nl> - auto exp1 = <nl> - HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , constant . get ( ) ) ; <nl> - auto exp2 = HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , exp1 . get ( ) ) ; <nl> + auto constant = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ) ; <nl> + auto exp1 = builder . AddInstruction ( <nl> + HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , constant ) ) ; <nl> + auto exp2 = builder . AddInstruction ( <nl> + HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , exp1 ) ) ; <nl> OpMetadata metadata ; <nl> metadata . set_op_name ( " tf_op " ) ; <nl> exp1 - > set_metadata ( metadata ) ; <nl> exp2 - > set_metadata ( metadata ) ; <nl> <nl> - auto fusion = HloInstruction : : CreateFusion ( <nl> - r0f32_ , HloInstruction : : FusionKind : : kLoop , exp2 . get ( ) ) ; <nl> - auto * fused = fusion - > FuseInstruction ( exp1 . get ( ) ) ; <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto * computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> + auto * fusion = computation - > CreateFusionInstruction ( <nl> + { exp2 , exp1 } , HloInstruction : : FusionKind : : kLoop ) ; <nl> + <nl> EXPECT_TRUE ( protobuf_util : : ProtobufEquals ( metadata , fusion - > metadata ( ) ) ) ; <nl> - EXPECT_TRUE ( protobuf_util : : ProtobufEquals ( metadata , fused - > metadata ( ) ) ) ; <nl> + EXPECT_TRUE ( protobuf_util : : ProtobufEquals ( <nl> + metadata , fusion - > fused_expression_root ( ) - > metadata ( ) ) ) ; <nl> + EXPECT_TRUE ( protobuf_util : : ProtobufEquals ( <nl> + metadata , fusion - > fused_expression_root ( ) - > operand ( 0 ) - > metadata ( ) ) ) ; <nl> } <nl> <nl> TEST_F ( HloInstructionTest , FusionOpWithCalledComputations ) { <nl> + HloComputation : : Builder builder ( TestName ( ) ) ; <nl> / / Create a fusion instruction containing a single unary operation . <nl> const Shape scalar_shape = ShapeUtil : : MakeShape ( F32 , { } ) ; <nl> <nl> TEST_F ( HloInstructionTest , FusionOpWithCalledComputations ) { <nl> std : : unique_ptr < HloComputation > computation_x = make_map_computation ( ) ; <nl> std : : unique_ptr < HloComputation > computation_y = make_map_computation ( ) ; <nl> <nl> - auto constant = <nl> - HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ; <nl> - auto map_1_x = <nl> - HloInstruction : : CreateMap ( scalar_shape , { constant . get ( ) } , <nl> - computation_x . get ( ) , / * static_operands = * / { } ) ; <nl> - auto map_2_x = <nl> - HloInstruction : : CreateMap ( scalar_shape , { map_1_x . get ( ) } , <nl> - computation_x . get ( ) , / * static_operands = * / { } ) ; <nl> - auto map_3_y = <nl> - HloInstruction : : CreateMap ( scalar_shape , { map_2_x . get ( ) } , <nl> - computation_y . get ( ) , / * static_operands = * / { } ) ; <nl> - <nl> - auto fusion = HloInstruction : : CreateFusion ( <nl> - scalar_shape , HloInstruction : : FusionKind : : kLoop , map_3_y . get ( ) ) ; <nl> - <nl> - EXPECT_THAT ( fusion - > called_computations ( ) , ElementsAre ( computation_y . get ( ) ) ) ; <nl> - <nl> - fusion - > FuseInstruction ( map_2_x . get ( ) ) ; <nl> + auto constant = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ) ; <nl> + auto map_1_x = builder . AddInstruction ( HloInstruction : : CreateMap ( <nl> + scalar_shape , { constant } , computation_x . get ( ) , / * static_operands = * / { } ) ) ; <nl> + auto map_2_x = builder . AddInstruction ( HloInstruction : : CreateMap ( <nl> + scalar_shape , { map_1_x } , computation_x . get ( ) , / * static_operands = * / { } ) ) ; <nl> + auto map_3_y = builder . AddInstruction ( HloInstruction : : CreateMap ( <nl> + scalar_shape , { map_2_x } , computation_y . get ( ) , / * static_operands = * / { } ) ) ; <nl> + <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto * computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> + auto * fusion = computation - > CreateFusionInstruction ( <nl> + { map_3_y } , HloInstruction : : FusionKind : : kLoop ) ; <nl> + auto * fused_computation = fusion - > fused_instructions_computation ( ) ; <nl> EXPECT_THAT ( fusion - > called_computations ( ) , <nl> - ElementsAre ( computation_y . get ( ) , computation_x . get ( ) ) ) ; <nl> + ElementsAre ( fused_computation , computation_y . get ( ) ) ) ; <nl> <nl> - fusion - > FuseInstruction ( map_1_x . get ( ) ) ; <nl> - EXPECT_THAT ( fusion - > called_computations ( ) , <nl> - ElementsAre ( computation_y . get ( ) , computation_x . get ( ) ) ) ; <nl> + fusion - > FuseInstruction ( map_2_x ) ; <nl> + EXPECT_THAT ( <nl> + fusion - > called_computations ( ) , <nl> + ElementsAre ( fused_computation , computation_y . get ( ) , computation_x . get ( ) ) ) ; <nl> + <nl> + fusion - > FuseInstruction ( map_1_x ) ; <nl> + EXPECT_THAT ( <nl> + fusion - > called_computations ( ) , <nl> + ElementsAre ( fused_computation , computation_y . get ( ) , computation_x . get ( ) ) ) ; <nl> } <nl> <nl> TEST_F ( HloInstructionTest , ComplexFusionOp ) { <nl> + HloComputation : : Builder builder ( TestName ( ) ) ; <nl> / / Fuse all instructions in complicated expression : <nl> / / <nl> / / add = Add ( C1 , C2 ) <nl> TEST_F ( HloInstructionTest , ComplexFusionOp ) { <nl> / / <nl> / / Notable complexities are repeated operands in a same instruction , different <nl> / / shapes , use of value in different expressions . <nl> - auto c1 = HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ; <nl> - auto c2 = HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 2 . 1f ) ) ; <nl> - auto c3 = HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 9 . 0f ) ) ; <nl> - <nl> - auto add = <nl> - HloInstruction : : CreateBinary ( r0f32_ , HloOpcode : : kAdd , c1 . get ( ) , c2 . get ( ) ) ; <nl> - auto clamp = HloInstruction : : CreateTernary ( r0f32_ , HloOpcode : : kClamp , <nl> - c2 . get ( ) , add . get ( ) , add . get ( ) ) ; <nl> - auto exp = HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , add . get ( ) ) ; <nl> - auto mul = HloInstruction : : CreateBinary ( r0f32_ , HloOpcode : : kMultiply , <nl> - exp . get ( ) , c3 . get ( ) ) ; <nl> - auto sub = HloInstruction : : CreateBinary ( r0f32_ , HloOpcode : : kSubtract , <nl> - mul . get ( ) , clamp . get ( ) ) ; <nl> + auto c1 = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 1 . 1f ) ) ) ; <nl> + auto c2 = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 2 . 1f ) ) ) ; <nl> + auto c3 = builder . AddInstruction ( <nl> + HloInstruction : : CreateConstant ( Literal : : CreateR0 < float > ( 9 . 0f ) ) ) ; <nl> + <nl> + auto add = builder . AddInstruction ( <nl> + HloInstruction : : CreateBinary ( r0f32_ , HloOpcode : : kAdd , c1 , c2 ) ) ; <nl> + auto clamp = builder . AddInstruction ( <nl> + HloInstruction : : CreateTernary ( r0f32_ , HloOpcode : : kClamp , c2 , add , add ) ) ; <nl> + auto exp = builder . AddInstruction ( <nl> + HloInstruction : : CreateUnary ( r0f32_ , HloOpcode : : kExp , add ) ) ; <nl> + auto mul = builder . AddInstruction ( <nl> + HloInstruction : : CreateBinary ( r0f32_ , HloOpcode : : kMultiply , exp , c3 ) ) ; <nl> + auto sub = builder . AddInstruction ( <nl> + HloInstruction : : CreateBinary ( r0f32_ , HloOpcode : : kSubtract , mul , clamp ) ) ; <nl> auto tuple = <nl> - HloInstruction : : CreateTuple ( { sub . get ( ) , sub . get ( ) , mul . get ( ) , c1 . get ( ) } ) ; <nl> + builder . AddInstruction ( HloInstruction : : CreateTuple ( { sub , sub , mul , c1 } ) ) ; <nl> <nl> - auto fusion = HloInstruction : : CreateFusion ( <nl> - r0f32_ , HloInstruction : : FusionKind : : kLoop , tuple . get ( ) ) ; <nl> - fusion - > FuseInstruction ( sub . get ( ) ) ; <nl> - fusion - > FuseInstruction ( mul . get ( ) ) ; <nl> - fusion - > FuseInstruction ( exp . get ( ) ) ; <nl> - fusion - > FuseInstruction ( clamp . get ( ) ) ; <nl> - fusion - > FuseInstruction ( add . get ( ) ) ; <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto * computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> + auto * fusion = computation - > CreateFusionInstruction ( <nl> + { tuple , sub , mul , exp , clamp , add } , HloInstruction : : FusionKind : : kLoop ) ; <nl> <nl> / / Operands in the fusion instruction ' s operands ( ) vector should be in the <nl> / / order in which their users were added fused . <nl> - EXPECT_THAT ( fusion - > operands ( ) , ElementsAre ( c1 . get ( ) , c3 . get ( ) , c2 . get ( ) ) ) ; <nl> - EXPECT_THAT ( c1 - > users ( ) , <nl> - UnorderedElementsAre ( add . get ( ) , tuple . get ( ) , fusion . get ( ) ) ) ; <nl> + EXPECT_THAT ( fusion - > operands ( ) , ElementsAre ( c1 , c3 , c2 ) ) ; <nl> + EXPECT_THAT ( c1 - > users ( ) , ElementsAre ( fusion ) ) ; <nl> } <nl> <nl> / / Convenience function for comparing two HloInstructions inside of <nl> TEST_F ( HloInstructionTest , PartiallyElementwise ) { <nl> HloInstruction * max = builder . AddInstruction ( <nl> HloInstruction : : CreateBinary ( r2f32 , HloOpcode : : kMaximum , div , broadcast ) ) ; <nl> <nl> - auto computation = builder . Build ( ) ; <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto * computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> HloInstruction * fusion = computation - > CreateFusionInstruction ( <nl> { max , broadcast , div , mul } , HloInstruction : : FusionKind : : kLoop ) ; <nl> EXPECT_FALSE ( fusion - > IsElementwise ( ) ) ; <nl> TEST_F ( HloInstructionTest , PartiallyElementwiseWithReuse ) { <nl> HloInstruction * sub = builder . AddInstruction ( HloInstruction : : CreateBinary ( <nl> r1f32 , HloOpcode : : kSubtract , min , broadcast ) ) ; <nl> <nl> - auto computation = builder . Build ( ) ; <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto * computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> HloInstruction * fusion = computation - > CreateFusionInstruction ( <nl> { sub , broadcast , min } , HloInstruction : : FusionKind : : kLoop ) ; <nl> EXPECT_FALSE ( fusion - > IsElementwise ( ) ) ; <nl> TEST_F ( HloInstructionTest , CloneOfFusionPreservesShape ) { <nl> HloInstruction * dot = builder . AddInstruction ( <nl> HloInstruction : : CreateBinary ( sout , HloOpcode : : kDot , x , reshape ) ) ; <nl> <nl> - auto computation = builder . Build ( ) ; <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto * computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> HloInstruction * fusion = computation - > CreateFusionInstruction ( <nl> { dot , reshape } , HloInstruction : : FusionKind : : kTransposeDot ) ; <nl> <nl> mmm a / tensorflow / compiler / xla / service / hlo_ordering . cc <nl> ppp b / tensorflow / compiler / xla / service / hlo_ordering . cc <nl> DependencyHloOrdering : : DependencyHloOrdering ( const HloModule * module ) <nl> / / ordering based on dependencies . ExecutesBefore will return true iff there <nl> / / exists a path in the HLO computation graph from ' a ' to ' b ' . <nl> for ( auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> predecessors_ . emplace ( computation . get ( ) , <nl> computation - > ComputeReachability ( ) ) ; <nl> } <nl> mmm a / tensorflow / compiler / xla / service / hlo_rematerialization . cc <nl> ppp b / tensorflow / compiler / xla / service / hlo_rematerialization . cc <nl> StatusOr < bool > HloRematerialization : : Run ( <nl> / / After DCE , the module sequence may include instructions which no longer <nl> / / exist . <nl> for ( const auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> if ( sequence - > at ( computation . get ( ) ) . size ( ) ! = <nl> computation - > instruction_count ( ) ) { <nl> / / A size mismatch between the computation instruction count and the size <nl> mmm a / tensorflow / compiler / xla / service / hlo_scheduling . cc <nl> ppp b / tensorflow / compiler / xla / service / hlo_scheduling . cc <nl> CreateMemoryMinimizingSequence ( <nl> TF_ASSIGN_OR_RETURN ( std : : unique_ptr < TuplePointsToAnalysis > points_to_analysis , <nl> TuplePointsToAnalysis : : Run ( & module ) ) ; <nl> for ( const auto & computation : module . computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> TF_ASSIGN_OR_RETURN ( sequence [ computation . get ( ) ] , <nl> CreateMemoryMinimizingSequence ( <nl> * computation , * points_to_analysis , size_function ) ) ; <nl> CreateMemoryMinimizingSequence ( <nl> StatusOr < std : : vector < const HloInstruction * > > CreateMemoryMinimizingSequence ( <nl> const HloComputation & computation , <nl> const LogicalBuffer : : SizeFunction & size_function ) { <nl> + CHECK ( ! computation . IsFusionComputation ( ) ) ; <nl> TF_ASSIGN_OR_RETURN ( std : : unique_ptr < TuplePointsToAnalysis > points_to_analysis , <nl> TuplePointsToAnalysis : : Run ( computation . parent ( ) ) ) ; <nl> return CreateMemoryMinimizingSequence ( computation , * points_to_analysis , <nl> mmm a / tensorflow / compiler / xla / service / instruction_fusion . cc <nl> ppp b / tensorflow / compiler / xla / service / instruction_fusion . cc <nl> bool InstructionFusion : : CanFuseOnAllPaths ( <nl> <nl> StatusOr < bool > InstructionFusion : : Run ( HloModule * module ) { <nl> bool changed = false ; <nl> + <nl> + std : : vector < HloComputation * > computations ; <nl> for ( auto & computation : module - > computations ( ) ) { <nl> - computation_ = computation . get ( ) ; <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> + computations . push_back ( computation . get ( ) ) ; <nl> + } <nl> + for ( auto & computation : computations ) { <nl> + CHECK ( ! computation - > IsFusionComputation ( ) ) ; <nl> + computation_ = computation ; <nl> <nl> / / We want to be able to remove arbitrary instructions from the post order <nl> / / and also compare positions of instructions in the post order . To make <nl> mmm a / tensorflow / compiler / xla / service / layout_assignment . cc <nl> ppp b / tensorflow / compiler / xla / service / layout_assignment . cc <nl> Status CheckLayouts ( <nl> TF_ASSIGN_OR_RETURN ( auto points_to_analysis , <nl> TuplePointsToAnalysis : : Run ( module ) ) ; <nl> for ( auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> for ( auto & instruction : computation - > instructions ( ) ) { <nl> / / Verify every instruction has a layout and the layout is valid for the <nl> / / shape . <nl> StatusOr < bool > LayoutAssignment : : Run ( HloModule * module ) { <nl> if ( computation = = module - > entry_computation ( ) ) { <nl> TF_RETURN_IF_ERROR ( RunOnComputation ( * entry_computation_layout_ , <nl> module - > entry_computation ( ) ) ) ; <nl> + } else if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> } else { <nl> ComputationLayout computation_layout ( computation - > ComputeProgramShape ( ) ) ; <nl> / / Setting all embedded computations to the default layout is potentially <nl> mmm a / tensorflow / compiler / xla / service / name_uniquer . cc <nl> ppp b / tensorflow / compiler / xla / service / name_uniquer . cc <nl> string NameUniquer : : GetUniqueName ( tensorflow : : StringPiece prefix ) { <nl> return root ; <nl> } else { <nl> tensorflow : : strings : : StrAppend ( & root , separator_ , * count ) ; <nl> + / / Increment lookup under old ' root ' name . <nl> ( * count ) + + ; <nl> + / / Initialize count under new ' root ' name . <nl> + count = & ( generated_names_ [ root ] ) ; <nl> + * count = 1 ; <nl> return root ; <nl> } <nl> } <nl> mmm a / tensorflow / compiler / xla / service / reduce_precision_insertion . cc <nl> ppp b / tensorflow / compiler / xla / service / reduce_precision_insertion . cc <nl> StatusOr < bool > ReducePrecisionInsertion : : Run ( HloModule * module ) { <nl> VLOG ( 1 ) < < " Running ReducePrecisionInsertion pass on " < < module - > name ( ) ; <nl> <nl> for ( auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> std : : vector < HloInstruction * > instructions_to_suffix ; <nl> <nl> for ( auto & instruction : computation - > instructions ( ) ) { <nl> mmm a / tensorflow / compiler / xla / service / reshape_mover . cc <nl> ppp b / tensorflow / compiler / xla / service / reshape_mover . cc <nl> StatusOr < bool > TrySinkReshapeOrTranspose ( HloComputation * computation , <nl> <nl> StatusOr < bool > ReshapeMover : : Run ( HloModule * module ) { <nl> bool changed = false ; <nl> - for ( const auto & comp : module - > computations ( ) ) { <nl> + std : : vector < HloComputation * > computations ; <nl> + for ( auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> + computations . push_back ( computation . get ( ) ) ; <nl> + } <nl> + for ( const auto & comp : computations ) { <nl> for ( HloInstruction * instruction : comp - > MakeInstructionPostOrder ( ) ) { <nl> TF_ASSIGN_OR_RETURN ( bool did_change , <nl> - TrySinkReshapeOrTranspose ( comp . get ( ) , instruction ) ) ; <nl> + TrySinkReshapeOrTranspose ( comp , instruction ) ) ; <nl> changed | = did_change ; <nl> } <nl> } <nl> mmm a / tensorflow / compiler / xla / service / reshape_mover_test . cc <nl> ppp b / tensorflow / compiler / xla / service / reshape_mover_test . cc <nl> TEST_F ( ReshapeMoverTest , EquivalentReshapesMovedAcrossFusion ) { <nl> auto add = builder . AddInstruction ( HloInstruction : : CreateBinary ( <nl> root_shape , HloOpcode : : kAdd , reshape0 , reshape1 ) ) ; <nl> <nl> - auto module = CreateNewModule ( ) ; <nl> - auto computation = module - > AddEntryComputation ( builder . Build ( ) ) ; <nl> - auto fusion = computation - > AddInstruction ( HloInstruction : : CreateFusion ( <nl> - add - > shape ( ) , HloInstruction : : FusionKind : : kLoop , add ) ) ; <nl> - TF_CHECK_OK ( computation - > ReplaceInstruction ( add , fusion ) ) ; <nl> + HloModule module ( TestName ( ) ) ; <nl> + auto computation = module . AddEntryComputation ( builder . Build ( ) ) ; <nl> + computation - > CreateFusionInstruction ( { add } , <nl> + HloInstruction : : FusionKind : : kLoop ) ; <nl> <nl> EXPECT_THAT ( computation - > root_instruction ( ) , <nl> op : : Fusion ( op : : Reshape ( param0 ) , op : : Reshape ( param1 ) ) ) ; <nl> <nl> - EXPECT_TRUE ( ReshapeMover ( ) . Run ( module . get ( ) ) . ValueOrDie ( ) ) ; <nl> + EXPECT_TRUE ( ReshapeMover ( ) . Run ( & module ) . ValueOrDie ( ) ) ; <nl> <nl> EXPECT_THAT ( computation - > root_instruction ( ) , <nl> op : : Reshape ( op : : Fusion ( param0 , param1 ) ) ) ; <nl> mmm a / tensorflow / compiler / xla / service / transpose_folding . cc <nl> ppp b / tensorflow / compiler / xla / service / transpose_folding . cc <nl> StatusOr < bool > TransposeFolding : : Run ( HloModule * module ) { <nl> return tensorflow : : Status : : OK ( ) ; <nl> } ; <nl> <nl> - for ( auto & comp : module - > computations ( ) ) { <nl> + std : : vector < HloComputation * > computations ; <nl> + for ( auto & computation : module - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> + computations . push_back ( computation . get ( ) ) ; <nl> + } <nl> + for ( auto & comp : computations ) { <nl> TF_RETURN_IF_ERROR ( comp - > Accept ( visit_fn ) ) ; <nl> } <nl> <nl> mmm a / tensorflow / compiler / xla / service / tuple_points_to_analysis . cc <nl> ppp b / tensorflow / compiler / xla / service / tuple_points_to_analysis . cc <nl> TuplePointsToAnalysis : : Run ( const HloModule * module ) { <nl> Status TuplePointsToAnalysis : : Analyze ( ) { <nl> points_to_ . clear ( ) ; <nl> for ( auto & computation : module_ - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> TF_RETURN_IF_ERROR ( computation - > Accept ( this ) ) ; <nl> TF_RETURN_IF_ERROR ( <nl> PopulateDefinedBuffersAndAliases ( computation - > instructions ( ) ) ) ; <nl> string TuplePointsToAnalysis : : ToString ( ) const { <nl> string output = tensorflow : : strings : : Printf ( <nl> " TuplePointsToSet for module % s : \ n " , module_ - > name ( ) . c_str ( ) ) ; <nl> for ( const auto & computation : module_ - > computations ( ) ) { <nl> + if ( computation - > IsFusionComputation ( ) ) { <nl> + continue ; <nl> + } <nl> const char * entry = <nl> computation . get ( ) = = module_ - > entry_computation ( ) ? " entry " : " " ; <nl> tensorflow : : strings : : StrAppend ( & output , entry , " computation " , <nl> mmm a / tensorflow / contrib / bayesflow / BUILD <nl> ppp b / tensorflow / contrib / bayesflow / BUILD <nl> py_library ( <nl> <nl> cuda_py_test ( <nl> name = " csiszar_divergence_test " , <nl> - size = " small " , <nl> + size = " medium " , <nl> srcs = [ " python / kernel_tests / csiszar_divergence_test . py " ] , <nl> additional_deps = [ <nl> " : bayesflow_py " , <nl> " / / third_party / py / numpy " , <nl> " / / tensorflow / contrib / distributions : distributions_py " , <nl> - " / / tensorflow / contrib / layers : layers_py " , <nl> " / / tensorflow / python / ops / distributions " , <nl> " / / tensorflow / python : array_ops " , <nl> " / / tensorflow / python : client_testlib " , <nl> " / / tensorflow / python : framework_for_generated_wrappers " , <nl> - " / / tensorflow / python : framework_test_lib " , <nl> " / / tensorflow / python : gradients " , <nl> " / / tensorflow / python : linalg_ops " , <nl> " / / tensorflow / python : math_ops " , <nl> " / / tensorflow / python : nn_ops " , <nl> - " / / tensorflow / python : platform_test " , <nl> ] , <nl> ) <nl> <nl> cuda_py_test ( <nl> " / / third_party / py / numpy " , <nl> " / / tensorflow / contrib / distributions : distributions_py " , <nl> " / / tensorflow / contrib / layers : layers_py " , <nl> + " / / tensorflow / python / ops / distributions " , <nl> " / / tensorflow / python : client_testlib " , <nl> " / / tensorflow / python : framework_for_generated_wrappers " , <nl> - " / / tensorflow / python : framework_test_lib " , <nl> " / / tensorflow / python : math_ops " , <nl> " / / tensorflow / python : nn_ops " , <nl> - " / / tensorflow / python : platform_test " , <nl> " / / tensorflow / python : variables " , <nl> ] , <nl> ) <nl> mmm a / tensorflow / contrib / bayesflow / python / kernel_tests / entropy_test . py <nl> ppp b / tensorflow / contrib / bayesflow / python / kernel_tests / entropy_test . py <nl> <nl> <nl> import numpy as np <nl> <nl> - from tensorflow . contrib import distributions as distributions_lib <nl> from tensorflow . contrib import layers as layers_lib <nl> - from tensorflow . contrib . bayesflow . python . ops import entropy_impl as entropy_lib <nl> + from tensorflow . contrib . bayesflow . python . ops import entropy_impl as entropy <nl> + from tensorflow . contrib . distributions . python . ops import mvn_diag as mvn_diag_lib <nl> + from tensorflow . contrib . distributions . python . ops import mvn_tril as mvn_tril_lib <nl> from tensorflow . python . framework import constant_op <nl> from tensorflow . python . framework import dtypes <nl> from tensorflow . python . ops import math_ops <nl> from tensorflow . python . ops import nn_ops <nl> from tensorflow . python . ops import variables <nl> + from tensorflow . python . ops . distributions import kullback_leibler as kullback_leibler_lib <nl> + from tensorflow . python . ops . distributions import normal as normal_lib <nl> + from tensorflow . python . ops . distributions import util as distribution_util <nl> from tensorflow . python . platform import test <nl> <nl> - distributions = distributions_lib <nl> layers = layers_lib <nl> - entropy = entropy_lib <nl> <nl> <nl> - class NormalNoEntropy ( distributions . Normal ) : # pylint : disable = no - init <nl> + class NormalNoEntropy ( normal_lib . Normal ) : # pylint : disable = no - init <nl> " " " Normal distribution without a ` . entropy ` method . " " " <nl> <nl> def entropy ( self ) : <nl> def test_convergence_to_kl_using_sample_form_on_3dim_normal ( self ) : <nl> n_samples = 5000 <nl> <nl> with self . test_session ( ) : <nl> - q = distributions . MultivariateNormalDiag ( <nl> + q = mvn_diag_lib . MultivariateNormalDiag ( <nl> loc = self . _rng . rand ( * vector_shape ) , <nl> scale_diag = self . _rng . rand ( * vector_shape ) ) <nl> - p = distributions . MultivariateNormalDiag ( <nl> + p = mvn_diag_lib . MultivariateNormalDiag ( <nl> loc = self . _rng . rand ( * vector_shape ) , <nl> scale_diag = self . _rng . rand ( * vector_shape ) ) <nl> <nl> def test_convergence_to_kl_using_sample_form_on_3dim_normal ( self ) : <nl> n = n_samples , <nl> form = entropy . ELBOForms . sample , <nl> seed = 42 ) <nl> - actual_kl = distributions . kl_divergence ( q , p ) <nl> + actual_kl = kullback_leibler_lib . kl_divergence ( q , p ) <nl> <nl> # Relative tolerance ( rtol ) chosen 2 times as large as minimim needed to <nl> # pass . <nl> def test_convergence_to_kl_using_analytic_entropy_form_on_3dim_normal ( self ) : <nl> <nl> vector_shape = ( 2 , 3 ) <nl> with self . test_session ( ) : <nl> - q = distributions . MultivariateNormalDiag ( <nl> + q = mvn_diag_lib . MultivariateNormalDiag ( <nl> loc = self . _rng . rand ( * vector_shape ) , <nl> scale_diag = self . _rng . rand ( * vector_shape ) ) <nl> - p = distributions . MultivariateNormalDiag ( <nl> + p = mvn_diag_lib . MultivariateNormalDiag ( <nl> loc = self . _rng . rand ( * vector_shape ) , <nl> scale_diag = self . _rng . rand ( * vector_shape ) ) <nl> <nl> def test_convergence_to_kl_using_analytic_entropy_form_on_3dim_normal ( self ) : <nl> n = n_samples , <nl> form = entropy . ELBOForms . analytic_entropy , <nl> seed = 42 ) <nl> - actual_kl = distributions . kl_divergence ( q , p ) <nl> + actual_kl = kullback_leibler_lib . kl_divergence ( q , p ) <nl> <nl> # Relative tolerance ( rtol ) chosen 2 times as large as minimim needed to <nl> # pass . <nl> def test_sample_kl_zero_when_p_and_q_are_the_same_distribution ( self ) : <nl> <nl> vector_shape = ( 2 , 3 ) <nl> with self . test_session ( ) : <nl> - q = distributions . MultivariateNormalDiag ( <nl> + q = mvn_diag_lib . MultivariateNormalDiag ( <nl> loc = self . _rng . rand ( * vector_shape ) , <nl> scale_diag = self . _rng . rand ( * vector_shape ) ) <nl> <nl> class EntropyShannonTest ( test . TestCase ) : <nl> <nl> def test_normal_entropy_default_form_uses_exact_entropy ( self ) : <nl> with self . test_session ( ) : <nl> - dist = distributions . Normal ( loc = 1 . 11 , scale = 2 . 22 ) <nl> + dist = normal_lib . Normal ( loc = 1 . 11 , scale = 2 . 22 ) <nl> mc_entropy = entropy . entropy_shannon ( dist , n = 11 ) <nl> exact_entropy = dist . entropy ( ) <nl> self . assertEqual ( exact_entropy . get_shape ( ) , mc_entropy . get_shape ( ) ) <nl> def test_normal_entropy_default_form_uses_exact_entropy ( self ) : <nl> <nl> def test_normal_entropy_analytic_form_uses_exact_entropy ( self ) : <nl> with self . test_session ( ) : <nl> - dist = distributions . Normal ( loc = 1 . 11 , scale = 2 . 22 ) <nl> + dist = normal_lib . Normal ( loc = 1 . 11 , scale = 2 . 22 ) <nl> mc_entropy = entropy . entropy_shannon ( <nl> dist , form = entropy . ELBOForms . analytic_entropy ) <nl> exact_entropy = dist . entropy ( ) <nl> def test_normal_entropy_analytic_form_uses_exact_entropy ( self ) : <nl> def test_normal_entropy_sample_form_gets_approximate_answer ( self ) : <nl> # Tested by showing we get a good answer that is not exact . <nl> with self . test_session ( ) : <nl> - dist = distributions . Normal ( loc = 1 . 11 , scale = 2 . 22 ) <nl> + dist = normal_lib . Normal ( loc = 1 . 11 , scale = 2 . 22 ) <nl> mc_entropy = entropy . entropy_shannon ( <nl> dist , n = 1000 , form = entropy . ELBOForms . sample , seed = 0 ) <nl> exact_entropy = dist . entropy ( ) <nl> def test_default_entropy_falls_back_on_sample_if_analytic_not_available ( self ) : <nl> # NormalNoEntropy is like a Normal , but does not have . entropy method , so <nl> # we are forced to fall back on sample entropy . <nl> dist_no_entropy = NormalNoEntropy ( loc = 1 . 11 , scale = 2 . 22 ) <nl> - dist_yes_entropy = distributions . Normal ( loc = 1 . 11 , scale = 2 . 22 ) <nl> + dist_yes_entropy = normal_lib . Normal ( loc = 1 . 11 , scale = 2 . 22 ) <nl> <nl> mc_entropy = entropy . entropy_shannon ( <nl> dist_no_entropy , n = 1000 , form = entropy . ELBOForms . sample , seed = 0 ) <nl> def test_fitting_two_dimensional_normal_n_equals_1000 ( self ) : <nl> mu_true = np . array ( [ 1 . 0 , - 1 . 0 ] , dtype = np . float64 ) <nl> chol_true = np . array ( [ [ 2 . 0 , 0 . 0 ] , [ 0 . 5 , 1 . 0 ] ] , dtype = np . float64 ) <nl> with self . test_session ( ) as sess : <nl> - target = distributions . MultivariateNormalTriL ( mu_true , chol_true ) <nl> + target = mvn_tril_lib . MultivariateNormalTriL ( mu_true , chol_true ) <nl> <nl> # Set up q distribution by defining mean / covariance as Variables <nl> mu = variables . Variable ( <nl> np . zeros ( mu_true . shape ) , dtype = mu_true . dtype , name = ' mu ' ) <nl> mat = variables . Variable ( <nl> np . zeros ( chol_true . shape ) , dtype = chol_true . dtype , name = ' mat ' ) <nl> - chol = distributions . matrix_diag_transform ( mat , transform = nn_ops . softplus ) <nl> - q = distributions . MultivariateNormalTriL ( mu , chol ) <nl> + chol = distribution_util . matrix_diag_transform ( <nl> + mat , transform = nn_ops . softplus ) <nl> + q = mvn_tril_lib . MultivariateNormalTriL ( mu , chol ) <nl> for alpha in [ 0 . 25 , 0 . 75 ] : <nl> <nl> negative_renyi_divergence = entropy . renyi_ratio ( <nl> def test_divergence_between_identical_distributions_is_zero ( self ) : <nl> n = 1000 <nl> vector_shape = ( 2 , 3 ) <nl> with self . test_session ( ) : <nl> - q = distributions . MultivariateNormalDiag ( <nl> + q = mvn_diag_lib . MultivariateNormalDiag ( <nl> loc = self . _rng . rand ( * vector_shape ) , <nl> scale_diag = self . _rng . rand ( * vector_shape ) ) <nl> for alpha in [ 0 . 25 , 0 . 75 ] : <nl> mmm a / tensorflow / contrib / distributions / BUILD <nl> ppp b / tensorflow / contrib / distributions / BUILD <nl> py_library ( <nl> srcs_version = " PY2AND3 " , <nl> deps = [ <nl> " : bijectors_py " , <nl> + " / / tensorflow / contrib / framework : framework_py " , <nl> + " / / tensorflow / contrib / learn " , <nl> " / / tensorflow / contrib / linalg : linalg_py " , <nl> " / / tensorflow / python : array_ops " , <nl> " / / tensorflow / python : check_ops " , <nl> - " / / tensorflow / python : client_testlib " , <nl> - " / / tensorflow / python : clip_ops " , <nl> " / / tensorflow / python : control_flow_ops " , <nl> " / / tensorflow / python : data_flow_ops " , <nl> " / / tensorflow / python : framework_for_generated_wrappers " , <nl> + " / / tensorflow / python : init_ops " , <nl> " / / tensorflow / python : linalg_ops " , <nl> " / / tensorflow / python : math_ops " , <nl> " / / tensorflow / python : nn " , <nl> " / / tensorflow / python : nn_ops " , <nl> " / / tensorflow / python : random_ops " , <nl> + " / / tensorflow / python : state_ops " , <nl> " / / tensorflow / python : tensor_util " , <nl> " / / tensorflow / python : util " , <nl> + " / / tensorflow / python : variable_scope " , <nl> " / / tensorflow / python / ops / distributions " , <nl> " / / third_party / py / numpy " , <nl> " @ six_archive / / : six " , <nl> ] , <nl> ) <nl> <nl> + cuda_py_test ( <nl> + name = " estimator_test " , <nl> + size = " small " , <nl> + srcs = [ " python / kernel_tests / estimator_test . py " ] , <nl> + additional_deps = [ <nl> + " : distributions_py " , <nl> + " / / third_party / py / numpy " , <nl> + " @ six_archive / / : six " , <nl> + " / / tensorflow / contrib / learn " , <nl> + " / / tensorflow / contrib / learn : head_test " , <nl> + " / / tensorflow / python / ops / distributions " , <nl> + " / / tensorflow / python : client_testlib " , <nl> + " / / tensorflow / python : framework_ops " , <nl> + " / / tensorflow / python : nn_ops " , <nl> + " / / tensorflow / python : session " , <nl> + ] , <nl> + ) <nl> + <nl> cuda_py_test ( <nl> name = " distribution_test " , <nl> size = " small " , <nl> mmm a / tensorflow / contrib / distributions / __init__ . py <nl> ppp b / tensorflow / contrib / distributions / __init__ . py <nl> <nl> from tensorflow . contrib . distributions . python . ops . deterministic import * <nl> from tensorflow . contrib . distributions . python . ops . distribution_util import matrix_diag_transform <nl> from tensorflow . contrib . distributions . python . ops . distribution_util import softplus_inverse <nl> + from tensorflow . contrib . distributions . python . ops . estimator import * <nl> from tensorflow . contrib . distributions . python . ops . geometric import * <nl> from tensorflow . contrib . distributions . python . ops . inverse_gamma import * <nl> from tensorflow . contrib . distributions . python . ops . logistic import * <nl> <nl> ' percentile ' , <nl> ' assign_exponential_moving_mean_variance ' , <nl> ' exponential_moving_mean_variance ' , <nl> + ' estimator_head_distribution_regression ' , <nl> ] <nl> <nl> remove_undocumented ( __name__ , _allowed_symbols ) <nl> new file mode 100644 <nl> index 0000000000000 . . 5ff0544c977a3 <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / distributions / python / kernel_tests / estimator_test . py <nl> <nl> + # Copyright 2017 The TensorFlow Authors . All Rights Reserved . <nl> + # <nl> + # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + # you may not use this file except in compliance with the License . <nl> + # You may obtain a copy of the License at <nl> + # <nl> + # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + # <nl> + # Unless required by applicable law or agreed to in writing , software <nl> + # distributed under the License is distributed on an " AS IS " BASIS , <nl> + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + # See the License for the specific language governing permissions and <nl> + # limitations under the License . <nl> + # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + " " " Tests for estimator . py . " " " <nl> + <nl> + from __future__ import absolute_import <nl> + from __future__ import division <nl> + from __future__ import print_function <nl> + <nl> + import numpy as np <nl> + import six <nl> + <nl> + from tensorflow . contrib . distributions . python . ops import estimator as estimator_lib <nl> + from tensorflow . contrib . learn . python . learn . estimators import constants <nl> + from tensorflow . contrib . learn . python . learn . estimators import head as head_lib <nl> + from tensorflow . contrib . learn . python . learn . estimators import model_fn <nl> + from tensorflow . contrib . learn . python . learn . estimators . head_test import _assert_metrics <nl> + from tensorflow . contrib . learn . python . learn . estimators . head_test import _assert_no_variables <nl> + from tensorflow . contrib . learn . python . learn . estimators . head_test import _assert_summary_tags <nl> + from tensorflow . python . client import session <nl> + from tensorflow . python . framework import ops <nl> + from tensorflow . python . ops import nn_ops <nl> + from tensorflow . python . ops . distributions import normal as normal_lib <nl> + from tensorflow . python . platform import test <nl> + <nl> + <nl> + class EstimatorHeadDistributionRegressionTest ( test . TestCase ) : <nl> + <nl> + def _assert_output_alternatives ( self , model_fn_ops ) : <nl> + self . assertEquals ( { <nl> + None : constants . ProblemType . LINEAR_REGRESSION <nl> + } , { <nl> + k : v [ 0 ] for k , v in six . iteritems ( model_fn_ops . output_alternatives ) <nl> + } ) <nl> + <nl> + def testNormalLocScaleLogits ( self ) : <nl> + # We will bias logits [ . . . , 1 ] so that : logits [ . . . , 1 ] = 0 implies scale = 1 . <nl> + scale_bias = np . log ( np . expm1 ( 1 . ) ) <nl> + <nl> + def softplus ( x ) : <nl> + return np . log1p ( np . exp ( x ) ) <nl> + <nl> + def actual_loss ( logits , labels ) : <nl> + mu = actual_mean ( logits ) <nl> + sigma = actual_stddev ( logits ) <nl> + labels = np . squeeze ( labels , - 1 ) <nl> + z = ( labels - mu ) / sigma <nl> + loss = 0 . 5 * ( z * * 2 . + np . log ( 2 . * np . pi ) ) + np . log ( sigma ) <nl> + return loss . mean ( ) <nl> + <nl> + def actual_mean ( logits ) : <nl> + return logits [ . . . , 0 ] <nl> + <nl> + def actual_stddev ( logits ) : <nl> + return softplus ( logits [ . . . , 1 ] + scale_bias ) <nl> + <nl> + def make_distribution_fn ( logits ) : <nl> + return normal_lib . Normal ( <nl> + loc = logits [ . . . , 0 ] , <nl> + scale = nn_ops . softplus ( logits [ . . . , 1 ] + scale_bias ) ) <nl> + <nl> + head = estimator_lib . estimator_head_distribution_regression ( <nl> + make_distribution_fn , <nl> + logits_dimension = 2 ) <nl> + labels = np . float32 ( [ [ - 1 . ] , <nl> + [ 0 . ] , <nl> + [ 1 . ] ] ) <nl> + logits = np . float32 ( [ [ 0 . , - 1 ] , <nl> + [ 1 , 0 . 5 ] , <nl> + [ - 1 , 1 ] ] ) <nl> + with ops . Graph ( ) . as_default ( ) , session . Session ( ) : <nl> + # Convert to tensor so we can index into head . distributions . <nl> + tflogits = ops . convert_to_tensor ( logits , name = " logits " ) <nl> + model_fn_ops = head . create_model_fn_ops ( <nl> + { } , <nl> + labels = labels , <nl> + mode = model_fn . ModeKeys . TRAIN , <nl> + train_op_fn = head_lib . no_op_train_fn , <nl> + logits = tflogits ) <nl> + self . _assert_output_alternatives ( model_fn_ops ) <nl> + _assert_summary_tags ( self , [ " loss " ] ) <nl> + _assert_no_variables ( self ) <nl> + loss = actual_loss ( logits , labels ) <nl> + _assert_metrics ( self , loss , { " loss " : loss } , model_fn_ops ) <nl> + <nl> + # Now we verify the underlying distribution was correctly constructed . <nl> + expected_mean = logits [ . . . , 0 ] <nl> + self . assertAllClose ( <nl> + expected_mean , <nl> + head . distribution ( tflogits ) . mean ( ) . eval ( ) , <nl> + rtol = 1e - 6 , atol = 0 . ) <nl> + <nl> + expected_stddev = softplus ( logits [ . . . , 1 ] + scale_bias ) <nl> + self . assertAllClose ( <nl> + expected_stddev , <nl> + head . distribution ( tflogits ) . stddev ( ) . eval ( ) , <nl> + rtol = 1e - 6 , atol = 0 . ) <nl> + # Should have created only one distribution . <nl> + self . assertEqual ( 1 , len ( head . distributions ) ) <nl> + <nl> + <nl> + if __name__ = = " __main__ " : <nl> + test . main ( ) <nl> new file mode 100644 <nl> index 0000000000000 . . 6b53338c4542c <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / distributions / python / ops / estimator . py <nl> <nl> + # Copyright 2017 The TensorFlow Authors . All Rights Reserved . <nl> + # <nl> + # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + # you may not use this file except in compliance with the License . <nl> + # You may obtain a copy of the License at <nl> + # <nl> + # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + # <nl> + # Unless required by applicable law or agreed to in writing , software <nl> + # distributed under the License is distributed on an " AS IS " BASIS , <nl> + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + # See the License for the specific language governing permissions and <nl> + # limitations under the License . <nl> + # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + " " " Functions to bridge ` Distribution ` s and ` tf . contrib . learn . estimator ` APIs . " " " <nl> + <nl> + from __future__ import absolute_import <nl> + from __future__ import division <nl> + from __future__ import print_function <nl> + <nl> + from tensorflow . contrib . learn . python . learn . estimators . head import _compute_weighted_loss <nl> + from tensorflow . contrib . learn . python . learn . estimators . head import _RegressionHead <nl> + from tensorflow . python . framework import ops <nl> + from tensorflow . python . framework import tensor_util <nl> + from tensorflow . python . ops import array_ops <nl> + <nl> + <nl> + __all__ = [ <nl> + " estimator_head_distribution_regression " , <nl> + ] <nl> + <nl> + <nl> + def estimator_head_distribution_regression ( make_distribution_fn , <nl> + label_dimension = 1 , <nl> + logits_dimension = None , <nl> + label_name = None , <nl> + weight_column_name = None , <nl> + enable_centered_bias = False , <nl> + head_name = None ) : <nl> + " " " Creates a ` Head ` for regression under a generic distribution . <nl> + <nl> + Args : <nl> + make_distribution_fn : Python ` callable ` which returns a ` tf . Distribution ` <nl> + instance created using only logits . <nl> + label_dimension : Number of regression labels per example . This is the size <nl> + of the last dimension of the labels ` Tensor ` ( typically , this has shape <nl> + ` [ batch_size , label_dimension ] ` ) . <nl> + logits_dimension : Number of logits per example . This is the size of the last <nl> + dimension of the logits ` Tensor ` ( typically , this has shape <nl> + ` [ batch_size , logits_dimension ] ` ) . <nl> + Default value : ` label_dimension ` . <nl> + label_name : Python ` str ` , name of the key in label ` dict ` . Can be ` None ` if <nl> + label is a ` Tensor ` ( single headed models ) . <nl> + weight_column_name : Python ` str ` defining feature column name representing <nl> + weights . It is used to down weight or boost examples during training . It <nl> + will be multiplied by the loss of the example . <nl> + enable_centered_bias : Python ` bool ` . If ` True ` , estimator will learn a <nl> + centered bias variable for each class . Rest of the model structure learns <nl> + the residual after centered bias . <nl> + head_name : Python ` str ` , name of the head . Predictions , summary and metrics <nl> + keys are suffixed by ` " / " + head_name ` and the default variable scope is <nl> + ` head_name ` . <nl> + <nl> + Returns : <nl> + An instance of ` Head ` for generic regression . <nl> + " " " <nl> + return _DistributionRegressionHead ( <nl> + make_distribution_fn = make_distribution_fn , <nl> + label_dimension = label_dimension , <nl> + logits_dimension = logits_dimension , <nl> + label_name = label_name , <nl> + weight_column_name = weight_column_name , <nl> + enable_centered_bias = enable_centered_bias , <nl> + head_name = head_name ) <nl> + <nl> + <nl> + class _DistributionRegressionHead ( _RegressionHead ) : <nl> + " " " Creates a _RegressionHead instance from an arbitray ` Distribution ` . " " " <nl> + <nl> + def __init__ ( self , <nl> + make_distribution_fn , <nl> + label_dimension , <nl> + logits_dimension = None , <nl> + label_name = None , <nl> + weight_column_name = None , <nl> + enable_centered_bias = False , <nl> + head_name = None ) : <nl> + " " " ` Head ` for regression . <nl> + <nl> + Args : <nl> + make_distribution_fn : Python ` callable ` which returns a ` tf . Distribution ` <nl> + instance created using only logits . <nl> + label_dimension : Number of regression labels per example . This is the <nl> + size of the last dimension of the labels ` Tensor ` ( typically , this has <nl> + shape ` [ batch_size , label_dimension ] ` ) . <nl> + logits_dimension : Number of logits per example . This is the size of the <nl> + last dimension of the logits ` Tensor ` ( typically , this has shape <nl> + ` [ batch_size , logits_dimension ] ` ) . <nl> + Default value : ` label_dimension ` . <nl> + label_name : Python ` str ` , name of the key in label ` dict ` . Can be ` None ` <nl> + if label is a tensor ( single headed models ) . <nl> + weight_column_name : Python ` str ` defining feature column name representing <nl> + weights . It is used to down weight or boost examples during training . It <nl> + will be multiplied by the loss of the example . <nl> + enable_centered_bias : Python ` bool ` . If ` True ` , estimator will learn a <nl> + centered bias variable for each class . Rest of the model structure <nl> + learns the residual after centered bias . <nl> + head_name : Python ` str ` , name of the head . Predictions , summary and <nl> + metrics keys are suffixed by ` " / " + head_name ` and the default variable <nl> + scope is ` head_name ` . <nl> + <nl> + Raises : <nl> + TypeError : if ` make_distribution_fn ` is not ` callable ` . <nl> + " " " <nl> + if not callable ( make_distribution_fn ) : <nl> + raise TypeError ( " ` make_distribution_fn ` must be a callable function . " ) <nl> + <nl> + self . _distributions = { } <nl> + self . _make_distribution_fn = make_distribution_fn <nl> + <nl> + def static_value ( x ) : <nl> + " " " Returns the static value of a ` Tensor ` or ` None ` . " " " <nl> + return tensor_util . constant_value ( ops . convert_to_tensor ( x ) ) <nl> + <nl> + def concat_vectors ( * args ) : <nl> + " " " Concatenates input vectors , statically if possible . " " " <nl> + args_ = [ static_value ( x ) for x in args ] <nl> + if any ( vec is None for vec in args_ ) : <nl> + return array_ops . concat ( args , axis = 0 ) <nl> + return [ val for vec in args_ for val in vec ] <nl> + <nl> + def loss_fn ( labels , logits , weights = None ) : <nl> + " " " Returns the loss of using ` logits ` to predict ` labels ` . " " " <nl> + d = self . distribution ( logits ) <nl> + labels_batch_shape = labels . shape . with_rank_at_least ( 1 ) [ : - 1 ] <nl> + labels_batch_shape = ( <nl> + labels_batch_shape . as_list ( ) if labels_batch_shape . is_fully_defined ( ) <nl> + else array_ops . shape ( labels ) [ : - 1 ] ) <nl> + labels = array_ops . reshape ( <nl> + labels , <nl> + shape = concat_vectors ( labels_batch_shape , d . event_shape_tensor ( ) ) ) <nl> + return _compute_weighted_loss ( <nl> + loss_unweighted = - d . log_prob ( labels ) , <nl> + weight = weights ) <nl> + <nl> + def link_fn ( logits ) : <nl> + " " " Returns the inverse link function at ` logits ` . " " " <nl> + # Note : What the API calls a " link function " is really the inverse - link <nl> + # function , i . e . , the " mean " . <nl> + d = self . distribution ( logits ) <nl> + return d . mean ( ) <nl> + <nl> + super ( _DistributionRegressionHead , self ) . __init__ ( <nl> + label_dimension = label_dimension , <nl> + loss_fn = loss_fn , <nl> + link_fn = link_fn , <nl> + logits_dimension = logits_dimension , <nl> + label_name = label_name , <nl> + weight_column_name = weight_column_name , <nl> + enable_centered_bias = enable_centered_bias , <nl> + head_name = head_name ) <nl> + <nl> + @ property <nl> + def distributions ( self ) : <nl> + " " " Returns all distributions created by ` DistributionRegressionHead ` . " " " <nl> + return self . _distributions <nl> + <nl> + def distribution ( self , logits , name = None ) : <nl> + " " " Retrieves a distribution instance , parameterized by ` logits ` . <nl> + <nl> + Args : <nl> + logits : ` float ` - like ` Tensor ` representing the parameters of the <nl> + underlying distribution . <nl> + name : The Python ` str ` name to given to this op . <nl> + Default value : " distribution " . <nl> + <nl> + Returns : <nl> + distribution : ` tf . Distribution ` instance parameterized by ` logits ` . <nl> + " " " <nl> + with ops . name_scope ( name , " distribution " , [ logits ] ) : <nl> + d = self . _distributions . get ( logits , None ) <nl> + if d is None : <nl> + d = self . _make_distribution_fn ( logits ) <nl> + self . _distributions [ logits ] = d <nl> + return d <nl> mmm a / tensorflow / contrib / distributions / python / ops / mvn_linear_operator . py <nl> ppp b / tensorflow / contrib / distributions / python / ops / mvn_linear_operator . py <nl> <nl> from __future__ import print_function <nl> <nl> from tensorflow . contrib import linalg <nl> - from tensorflow . contrib . distributions . python . ops import bijectors <nl> from tensorflow . contrib . distributions . python . ops import distribution_util <nl> + from tensorflow . contrib . distributions . python . ops . bijectors import AffineLinearOperator <nl> from tensorflow . python . framework import ops <nl> from tensorflow . python . ops import array_ops <nl> from tensorflow . python . ops import linalg_ops <nl> def __init__ ( self , <nl> distribution = normal . Normal ( <nl> loc = array_ops . zeros ( [ ] , dtype = scale . dtype ) , <nl> scale = array_ops . ones ( [ ] , dtype = scale . dtype ) ) , <nl> - bijector = bijectors . AffineLinearOperator ( <nl> + bijector = AffineLinearOperator ( <nl> shift = loc , scale = scale , validate_args = validate_args ) , <nl> batch_shape = batch_shape , <nl> event_shape = event_shape , <nl> mmm a / tensorflow / contrib / layers / python / layers / layers . py <nl> ppp b / tensorflow / contrib / layers / python / layers / layers . py <nl> <nl> + # - * - coding : utf - 8 - * - <nl> # Copyright 2016 The TensorFlow Authors . All Rights Reserved . <nl> # <nl> # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> <nl> from tensorflow . python . framework import function <nl> from tensorflow . python . framework import ops <nl> from tensorflow . python . framework import sparse_tensor <nl> + from tensorflow . python . framework import tensor_shape <nl> + from tensorflow . python . layers import base <nl> from tensorflow . python . layers import convolutional as convolutional_layers <nl> from tensorflow . python . layers import core as core_layers <nl> - from tensorflow . python . layers import normalization as normalization_layers <nl> + from tensorflow . python . layers import normalization as normalization_layers <nl> from tensorflow . python . layers import pooling as pooling_layers <nl> from tensorflow . python . ops import array_ops <nl> from tensorflow . python . ops import check_ops <nl> from tensorflow . python . ops import init_ops <nl> + from tensorflow . python . ops import linalg_ops <nl> from tensorflow . python . ops import math_ops <nl> from tensorflow . python . ops import nn <nl> from tensorflow . python . ops import sparse_ops <nl> def convolution3d_transpose ( <nl> trainable = True , <nl> scope = None ) : <nl> " " " Adds a convolution3d_transpose with an optional batch normalization layer . <nl> - <nl> + <nl> The function creates a variable called ` weights ` , representing the <nl> kernel , that is convolved with the input . If ` batch_norm_params ` is ` None ` , a <nl> second variable called ' biases ' is added to the result of the operation . <nl> def layer_norm ( inputs , <nl> outputs ) <nl> <nl> <nl> + class GDN ( base . Layer ) : <nl> + " " " Generalized divisive normalization layer . <nl> + <nl> + Based on the papers : <nl> + <nl> + " Density Modeling of Images using a Generalized Normalization <nl> + Transformation " <nl> + Johannes Ballé , Valero Laparra , Eero P . Simoncelli <nl> + https : / / arxiv . org / abs / 1511 . 06281 <nl> + <nl> + " End - to - end Optimized Image Compression " <nl> + Johannes Ballé , Valero Laparra , Eero P . Simoncelli <nl> + https : / / arxiv . org / abs / 1611 . 01704 <nl> + <nl> + Implements an activation function that is essentially a multivariate <nl> + generalization of a particular sigmoid - type function : <nl> + <nl> + y [ i ] = x [ i ] / sqrt ( beta [ i ] + sum_j ( gamma [ j , i ] * x [ j ] ) ) <nl> + <nl> + where i and j run over channels . This implementation never sums across spatial <nl> + dimensions . It is similar to local response normalization , but more powerful , <nl> + as beta and gamma are trainable parameters . <nl> + <nl> + Arguments : <nl> + inverse : If False ( default ) , compute GDN response . If True , compute IGDN <nl> + response ( one step of fixed point iteration to invert GDN ; the division <nl> + is replaced by multiplication ) . <nl> + beta_min : Lower bound for beta , to prevent numerical error from causing <nl> + square root of zero or negative values . <nl> + gamma_init : The gamma matrix will be initialized as the identity matrix <nl> + multiplied with this value . If set to zero , the layer is effectively <nl> + initialized to the identity operation , since beta is initialized as one . <nl> + A good default setting is somewhere between 0 and 0 . 5 . <nl> + reparam_offset : Offset added to the reparameterization of beta and gamma . <nl> + The reparameterization of beta and gamma as their square roots lets the <nl> + training slow down when their values are close to zero , which is desirable <nl> + as small values in the denominator can lead to a situation where gradient <nl> + noise on beta / gamma leads to extreme amounts of noise in the GDN <nl> + activations . However , without the offset , we would get zero gradients if <nl> + any elements of beta or gamma were exactly zero , and thus the training <nl> + could get stuck . To prevent this , we add this small constant . The default <nl> + value was empirically determined as a good starting point . Making it <nl> + bigger potentially leads to more gradient noise on the activations , making <nl> + it too small may lead to numerical precision issues . <nl> + data_format : Format of input tensor . Currently supports ' channels_first ' and <nl> + ' channels_last ' . <nl> + trainable : Boolean , if ` True ` also add variables to the graph collection <nl> + ` GraphKeys . TRAINABLE_VARIABLES ` ( see ` tf . Variable ` ) . <nl> + name : String , the name of the layer . Layers with the same name will <nl> + share weights , but to avoid mistakes we require reuse = True in such cases . <nl> + reuse : Boolean , whether to reuse the weights of a previous layer <nl> + by the same name . <nl> + <nl> + Properties : <nl> + inverse : Boolean , whether GDN is computed ( True ) or IGDN ( False ) . <nl> + data_format : Format of input tensor . Currently supports ' channels_first ' and <nl> + ' channels_last ' . <nl> + beta : The beta parameter as defined above ( 1D TensorFlow tensor ) . <nl> + gamma : The gamma parameter as defined above ( 2D TensorFlow tensor ) . <nl> + " " " <nl> + <nl> + def __init__ ( self , <nl> + inverse = False , <nl> + beta_min = 1e - 6 , <nl> + gamma_init = . 1 , <nl> + reparam_offset = 2 * * - 18 , <nl> + data_format = ' channels_last ' , <nl> + trainable = True , <nl> + name = None , <nl> + * * kwargs ) : <nl> + super ( GDN , self ) . __init__ ( trainable = trainable , name = name , * * kwargs ) <nl> + self . inverse = inverse <nl> + self . _beta_min = beta_min <nl> + self . _gamma_init = gamma_init <nl> + self . _reparam_offset = reparam_offset <nl> + self . data_format = data_format <nl> + self . _channel_axis ( ) # trigger ValueError early <nl> + self . input_spec = base . InputSpec ( min_ndim = 3 , max_ndim = 5 ) <nl> + <nl> + def _channel_axis ( self ) : <nl> + try : <nl> + return { ' channels_first ' : 1 , ' channels_last ' : - 1 } [ self . data_format ] <nl> + except KeyError : <nl> + raise ValueError ( ' Unsupported ` data_format ` for GDN layer : { } . ' . format ( <nl> + self . data_format ) ) <nl> + <nl> + @ staticmethod <nl> + def _lower_bound ( inputs , bound , name = None ) : <nl> + " " " Same as tf . maximum , but with helpful gradient for inputs < bound . <nl> + <nl> + The gradient is overwritten so that it is passed through if the input is not <nl> + hitting the bound . If it is , only gradients that push ` inputs ` higher than <nl> + the bound are passed through . No gradients are passed through to the bound . <nl> + <nl> + Args : <nl> + inputs : input tensor <nl> + bound : lower bound for the input tensor <nl> + name : name for this op <nl> + <nl> + Returns : <nl> + tf . maximum ( inputs , bound ) <nl> + " " " <nl> + with ops . name_scope ( name , ' GDNLowerBound ' , [ inputs , bound ] ) as scope : <nl> + inputs = ops . convert_to_tensor ( inputs , name = ' inputs ' ) <nl> + bound = ops . convert_to_tensor ( bound , name = ' bound ' ) <nl> + with ops . get_default_graph ( ) . gradient_override_map ( <nl> + { ' Maximum ' : ' GDNLowerBound ' } ) : <nl> + return math_ops . maximum ( inputs , bound , name = scope ) <nl> + <nl> + @ ops . RegisterGradient ( ' GDNLowerBound ' ) <nl> + @ staticmethod <nl> + def _lower_bound_grad ( op , grad ) : <nl> + " " " Gradient for ` _lower_bound ` . <nl> + <nl> + Args : <nl> + op : the tensorflow op for which to calculate a gradient <nl> + grad : gradient with respect to the output of the op <nl> + <nl> + Returns : <nl> + gradients with respect to the inputs of the op <nl> + " " " <nl> + inputs = op . inputs [ 0 ] <nl> + bound = op . inputs [ 1 ] <nl> + pass_through_if = math_ops . logical_or ( inputs > = bound , grad < 0 ) <nl> + return [ math_ops . cast ( pass_through_if , grad . dtype ) * grad , None ] <nl> + <nl> + def build ( self , input_shape ) : <nl> + channel_axis = self . _channel_axis ( ) <nl> + input_shape = tensor_shape . TensorShape ( input_shape ) <nl> + num_channels = input_shape [ channel_axis ] . value <nl> + if num_channels is None : <nl> + raise ValueError ( ' The channel dimension of the inputs to ` GDN ` ' <nl> + ' must be defined . ' ) <nl> + self . _input_rank = input_shape . ndims <nl> + self . input_spec = base . InputSpec ( ndim = input_shape . ndims , <nl> + axes = { channel_axis : num_channels } ) <nl> + <nl> + pedestal = array_ops . constant ( self . _reparam_offset * * 2 , dtype = self . dtype ) <nl> + beta_bound = array_ops . constant ( <nl> + ( self . _beta_min + self . _reparam_offset * * 2 ) * * . 5 , dtype = self . dtype ) <nl> + gamma_bound = array_ops . constant ( self . _reparam_offset , dtype = self . dtype ) <nl> + <nl> + def beta_initializer ( shape , dtype = None , partition_info = None ) : <nl> + del partition_info # unused <nl> + return math_ops . sqrt ( array_ops . ones ( shape , dtype = dtype ) + pedestal ) <nl> + <nl> + def gamma_initializer ( shape , dtype = None , partition_info = None ) : <nl> + del partition_info # unused <nl> + assert len ( shape ) = = 2 <nl> + assert shape [ 0 ] = = shape [ 1 ] <nl> + eye = linalg_ops . eye ( shape [ 0 ] , dtype = dtype ) <nl> + return math_ops . sqrt ( self . _gamma_init * eye + pedestal ) <nl> + <nl> + beta = self . add_variable ( ' reparam_beta ' , <nl> + shape = [ num_channels ] , <nl> + initializer = beta_initializer , <nl> + dtype = self . dtype , <nl> + trainable = True ) <nl> + beta = self . _lower_bound ( beta , beta_bound ) <nl> + self . beta = math_ops . square ( beta ) - pedestal <nl> + <nl> + gamma = self . add_variable ( ' reparam_gamma ' , <nl> + shape = [ num_channels , num_channels ] , <nl> + initializer = gamma_initializer , <nl> + dtype = self . dtype , <nl> + trainable = True ) <nl> + gamma = self . _lower_bound ( gamma , gamma_bound ) <nl> + self . gamma = math_ops . square ( gamma ) - pedestal <nl> + <nl> + self . built = True <nl> + <nl> + def call ( self , inputs ) : <nl> + inputs = ops . convert_to_tensor ( inputs , dtype = self . dtype ) <nl> + ndim = self . _input_rank <nl> + <nl> + shape = self . gamma . get_shape ( ) . as_list ( ) <nl> + gamma = array_ops . reshape ( self . gamma , ( ndim - 2 ) * [ 1 ] + shape ) <nl> + <nl> + # Compute normalization pool . <nl> + if self . data_format = = ' channels_first ' : <nl> + norm_pool = nn . convolution ( math_ops . square ( inputs ) , gamma , ' VALID ' , <nl> + data_format = ' NC ' + ' DHW ' [ - ( ndim - 2 ) : ] ) <nl> + if ndim = = 3 : <nl> + norm_pool = array_ops . expand_dims ( norm_pool , 2 ) <nl> + norm_pool = nn . bias_add ( norm_pool , self . beta , data_format = ' NCHW ' ) <nl> + norm_pool = array_ops . squeeze ( norm_pool , [ 2 ] ) <nl> + elif ndim = = 5 : <nl> + shape = array_ops . shape ( norm_pool ) <nl> + norm_pool = array_ops . reshape ( norm_pool , shape [ : 3 ] + [ - 1 ] ) <nl> + norm_pool = nn . bias_add ( norm_pool , self . beta , data_format = ' NCHW ' ) <nl> + norm_pool = array_ops . reshape ( norm_pool , shape ) <nl> + else : # ndim = = 4 <nl> + norm_pool = nn . bias_add ( norm_pool , self . beta , data_format = ' NCHW ' ) <nl> + else : # channels_last <nl> + norm_pool = nn . convolution ( math_ops . square ( inputs ) , gamma , ' VALID ' ) <nl> + norm_pool = nn . bias_add ( norm_pool , self . beta , data_format = ' NHWC ' ) <nl> + norm_pool = math_ops . sqrt ( norm_pool ) <nl> + <nl> + if self . inverse : <nl> + outputs = inputs * norm_pool <nl> + else : <nl> + outputs = inputs / norm_pool <nl> + outputs . set_shape ( inputs . get_shape ( ) ) <nl> + return outputs <nl> + <nl> + def _compute_output_shape ( self , input_shape ) : <nl> + channel_axis = self . _channel_axis ( ) <nl> + input_shape = tensor_shape . TensorShape ( input_shape ) <nl> + if not 3 < = input_shape . ndim < = 5 : <nl> + raise ValueError ( ' ` input_shape ` must be of rank 3 to 5 , inclusive . ' ) <nl> + if input_shape [ channel_axis ] . value is None : <nl> + raise ValueError ( <nl> + ' The channel dimension of ` input_shape ` must be defined . ' ) <nl> + return input_shape <nl> + <nl> + <nl> + def gdn ( inputs , <nl> + inverse = False , <nl> + beta_min = 1e - 6 , <nl> + gamma_init = . 1 , <nl> + reparam_offset = 2 * * - 18 , <nl> + data_format = ' channels_last ' , <nl> + trainable = True , <nl> + name = None , <nl> + reuse = None ) : <nl> + " " " Functional interface for GDN layer . <nl> + <nl> + Based on the papers : <nl> + <nl> + " Density Modeling of Images using a Generalized Normalization <nl> + Transformation " <nl> + Johannes Ballé , Valero Laparra , Eero P . Simoncelli <nl> + https : / / arxiv . org / abs / 1511 . 06281 <nl> + <nl> + " End - to - end Optimized Image Compression " <nl> + Johannes Ballé , Valero Laparra , Eero P . Simoncelli <nl> + https : / / arxiv . org / abs / 1611 . 01704 <nl> + <nl> + Implements an activation function that is essentially a multivariate <nl> + generalization of a particular sigmoid - type function : <nl> + <nl> + y [ i ] = x [ i ] / sqrt ( beta [ i ] + sum_j ( gamma [ j , i ] * x [ j ] ) ) <nl> + <nl> + where i and j run over channels . This implementation never sums across spatial <nl> + dimensions . It is similar to local response normalization , but more powerful , <nl> + as beta and gamma are trainable parameters . <nl> + <nl> + Arguments : <nl> + inputs : Tensor input . <nl> + inverse : If False ( default ) , compute GDN response . If True , compute IGDN <nl> + response ( one step of fixed point iteration to invert GDN ; the division <nl> + is replaced by multiplication ) . <nl> + beta_min : Lower bound for beta , to prevent numerical error from causing <nl> + square root of zero or negative values . <nl> + gamma_init : The gamma matrix will be initialized as the identity matrix <nl> + multiplied with this value . If set to zero , the layer is effectively <nl> + initialized to the identity operation , since beta is initialized as one . <nl> + A good default setting is somewhere between 0 and 0 . 5 . <nl> + reparam_offset : Offset added to the reparameterization of beta and gamma . <nl> + The reparameterization of beta and gamma as their square roots lets the <nl> + training slow down when their values are close to zero , which is desirable <nl> + as small values in the denominator can lead to a situation where gradient <nl> + noise on beta / gamma leads to extreme amounts of noise in the GDN <nl> + activations . However , without the offset , we would get zero gradients if <nl> + any elements of beta or gamma were exactly zero , and thus the training <nl> + could get stuck . To prevent this , we add this small constant . The default <nl> + value was empirically determined as a good starting point . Making it <nl> + bigger potentially leads to more gradient noise on the activations , making <nl> + it too small may lead to numerical precision issues . <nl> + data_format : Format of input tensor . Currently supports ' channels_first ' and <nl> + ' channels_last ' . <nl> + trainable : Boolean , if ` True ` also add variables to the graph collection <nl> + ` GraphKeys . TRAINABLE_VARIABLES ` ( see ` tf . Variable ` ) . <nl> + name : String , the name of the layer . Layers with the same name will <nl> + share weights , but to avoid mistakes we require reuse = True in such cases . <nl> + reuse : Boolean , whether to reuse the weights of a previous layer <nl> + by the same name . <nl> + <nl> + Returns : <nl> + Output tensor . <nl> + " " " <nl> + layer = GDN ( inverse = inverse , <nl> + beta_min = beta_min , <nl> + gamma_init = gamma_init , <nl> + reparam_offset = reparam_offset , <nl> + data_format = data_format , <nl> + trainable = trainable , <nl> + name = name , <nl> + dtype = inputs . dtype . base_dtype , <nl> + _scope = name , <nl> + _reuse = reuse ) <nl> + return layer . apply ( inputs ) <nl> + <nl> + <nl> @ add_arg_scope <nl> def max_pool2d ( inputs , <nl> kernel_size , <nl> mmm a / tensorflow / contrib / layers / python / layers / layers_test . py <nl> ppp b / tensorflow / contrib / layers / python / layers / layers_test . py <nl> def testOutputBigInput ( self ) : <nl> self . doOutputTest ( ( 1 , 100 , 100 , 1 ) ) <nl> <nl> <nl> + class GDNTest ( test . TestCase ) : <nl> + <nl> + def _runGDN ( self , x , shape , inverse , data_format ) : <nl> + inputs = array_ops . placeholder ( dtypes . float32 , shape ) <nl> + outputs = _layers . gdn ( inputs , inverse = inverse , data_format = data_format ) <nl> + with self . test_session ( ) as sess : <nl> + variables_lib . global_variables_initializer ( ) . run ( ) <nl> + y , = sess . run ( [ outputs ] , { inputs : x } ) <nl> + return y <nl> + <nl> + def testInvalidDataFormat ( self ) : <nl> + x = np . random . uniform ( size = ( 1 , 2 , 3 , 4 ) ) <nl> + with self . assertRaises ( ValueError ) : <nl> + self . _runGDN ( x , x . shape , False , ' NHWC ' ) <nl> + <nl> + def testUnknownDim ( self ) : <nl> + x = np . random . uniform ( size = ( 1 , 2 , 3 , 4 ) ) <nl> + with self . assertRaises ( ValueError ) : <nl> + self . _runGDN ( x , 4 * [ None ] , False , ' channels_last ' ) <nl> + <nl> + def testChannelsLast ( self ) : <nl> + for ndim in [ 3 , 4 , 5 ] : <nl> + x = np . random . uniform ( size = ( 1 , 2 , 3 , 4 ) [ : ndim ] ) <nl> + y = self . _runGDN ( x , x . shape , False , ' channels_last ' ) <nl> + self . assertEqual ( x . shape , y . shape ) <nl> + self . assertAllClose ( y , x / np . sqrt ( 1 + . 1 * ( x * * 2 ) ) , rtol = 0 , atol = 1e - 6 ) <nl> + <nl> + def testChannelsFirst ( self ) : <nl> + # ` bias_add ` doesn ' t support NCHW on CPU . <nl> + if test . is_gpu_available ( cuda_only = True ) : <nl> + for ndim in [ 3 , 4 , 5 ] : <nl> + x = np . random . uniform ( size = ( 4 , 3 , 2 , 1 ) [ : ndim ] ) <nl> + y = self . _runGDN ( x , x . shape , False , ' channels_first ' ) <nl> + self . assertEqual ( x . shape , y . shape ) <nl> + self . assertAllClose ( <nl> + y , x / np . sqrt ( 1 + . 1 * ( x * * 2 ) ) , rtol = 0 , atol = 1e - 6 ) <nl> + <nl> + def testWrongDims ( self ) : <nl> + for ndim in [ 1 , 2 , 6 ] : <nl> + x = np . random . uniform ( size = ( 1 , 2 , 3 , 4 , 3 , 2 ) [ : ndim ] ) <nl> + with self . assertRaises ( ValueError ) : <nl> + self . _runGDN ( x , x . shape , False , ' channels_last ' ) <nl> + <nl> + def testIGDN ( self ) : <nl> + x = np . random . uniform ( size = ( 1 , 2 , 3 , 4 ) ) <nl> + y = self . _runGDN ( x , x . shape , True , ' channels_last ' ) <nl> + self . assertEqual ( x . shape , y . shape ) <nl> + self . assertAllClose ( y , x * np . sqrt ( 1 + . 1 * ( x * * 2 ) ) , rtol = 0 , atol = 1e - 6 ) <nl> + <nl> + <nl> class MaxPool2DTest ( test . TestCase ) : <nl> <nl> def testInvalidDataFormat ( self ) : <nl> mmm a / tensorflow / contrib / learn / python / learn / estimators / head . py <nl> ppp b / tensorflow / contrib / learn / python / learn / estimators / head . py <nl> def __init__ ( self , <nl> label_dimension , <nl> loss_fn , <nl> link_fn , <nl> + logits_dimension = None , <nl> label_name = None , <nl> weight_column_name = None , <nl> enable_centered_bias = False , <nl> def __init__ ( self , <nl> shape ` [ batch_size , label_dimension ] ` ) . <nl> loss_fn : Loss function , takes logits and labels and returns loss . <nl> link_fn : Link function , takes a logits tensor and returns the output . <nl> + logits_dimension : Number of logits per example . This is the <nl> + size of the last dimension of the logits ` Tensor ` ( typically , this has <nl> + shape ` [ batch_size , label_dimension ] ` ) . <nl> + Default value : ` label_dimension ` . <nl> label_name : String , name of the key in label dict . Can be null if label <nl> is a tensor ( single headed models ) . <nl> weight_column_name : A string defining feature column name representing <nl> def __init__ ( self , <nl> " " " <nl> super ( _RegressionHead , self ) . __init__ ( <nl> problem_type = constants . ProblemType . LINEAR_REGRESSION , <nl> - logits_dimension = label_dimension , <nl> + logits_dimension = ( logits_dimension if logits_dimension is not None <nl> + else label_dimension ) , <nl> label_name = label_name , <nl> weight_column_name = weight_column_name , <nl> head_name = head_name ) <nl> mmm a / tensorflow / contrib / signal / python / ops / spectral_ops . py <nl> ppp b / tensorflow / contrib / signal / python / ops / spectral_ops . py <nl> def stft ( signals , frame_length , frame_step , fft_length = None , <nl> def inverse_stft ( stfts , <nl> frame_length , <nl> frame_step , <nl> - fft_length , <nl> + fft_length = None , <nl> window_fn = functools . partial ( window_ops . hann_window , <nl> periodic = True ) , <nl> name = None ) : <nl> def inverse_stft ( stfts , <nl> frame_length : An integer scalar ` Tensor ` . The window length in samples . <nl> frame_step : An integer scalar ` Tensor ` . The number of samples to step . <nl> fft_length : An integer scalar ` Tensor ` . The size of the FFT that produced <nl> - ` stfts ` . <nl> + ` stfts ` . If not provided , uses the smallest power of 2 enclosing <nl> + ` frame_length ` . <nl> window_fn : A callable that takes a window length and a ` dtype ` keyword <nl> argument and returns a ` [ window_length ] ` ` Tensor ` of samples in the <nl> provided datatype . If set to ` None ` , no windowing is used . <nl> def inverse_stft ( stfts , <nl> <nl> Raises : <nl> ValueError : If ` stfts ` is not at least rank 2 , ` frame_length ` is not scalar , <nl> - ` frame_step ` is not scalar , or ` fft_length ` is not scalar . <nl> + ` frame_step ` is not scalar , or ` fft_length ` is not scalar , or <nl> + ` frame_length ` is greater than ` fft_length ` . <nl> <nl> [ stft ] : https : / / en . wikipedia . org / wiki / Short - time_Fourier_transform <nl> " " " <nl> def inverse_stft ( stfts , <nl> frame_length . shape . assert_has_rank ( 0 ) <nl> frame_step = ops . convert_to_tensor ( frame_step , name = ' frame_step ' ) <nl> frame_step . shape . assert_has_rank ( 0 ) <nl> - fft_length = ops . convert_to_tensor ( fft_length , name = ' fft_length ' ) <nl> - fft_length . shape . assert_has_rank ( 0 ) <nl> + if fft_length is None : <nl> + fft_length = _enclosing_power_of_two ( frame_length ) <nl> + else : <nl> + fft_length = ops . convert_to_tensor ( fft_length , name = ' fft_length ' ) <nl> + fft_length . shape . assert_has_rank ( 0 ) <nl> + <nl> + frame_length_static = tensor_util . constant_value ( <nl> + frame_length ) <nl> + fft_length_static = tensor_util . constant_value ( fft_length ) <nl> + if ( frame_length_static is not None and fft_length_static is not None and <nl> + frame_length_static > fft_length_static ) : <nl> + raise ValueError ( ' frame_length ( % d ) may not be larger than ' <nl> + ' fft_length ( % d ) ' % ( frame_length_static , <nl> + fft_length_static ) ) <nl> + <nl> real_frames = spectral_ops . irfft ( stfts , [ fft_length ] ) [ . . . , : frame_length ] <nl> <nl> # Optionally window and overlap - add the inner 2 dimensions of real_frames <nl> mmm a / tensorflow / core / common_runtime / direct_session . h <nl> ppp b / tensorflow / core / common_runtime / direct_session . h <nl> class DirectSession : public Session { <nl> : : tensorflow : : Status ListDevices ( <nl> std : : vector < DeviceAttributes > * response ) override ; <nl> : : tensorflow : : Status Close ( ) override ; <nl> + : : tensorflow : : Status LocalDeviceManager ( const DeviceMgr * * output ) override { <nl> + * output = device_mgr_ . get ( ) ; <nl> + return : : tensorflow : : Status : : OK ( ) ; <nl> + } <nl> <nl> void ExportCostModels ( CostModelManager : : CostModelMap * cost_models ) { <nl> cost_model_manager_ . ExportCostModels ( cost_models ) ; <nl> } <nl> <nl> private : <nl> - typedef DirectSession ME ; <nl> - <nl> / / We create one executor and its dependent library runtime for <nl> / / every partition . <nl> struct PerPartitionExecutorsAndLib { <nl> mmm a / tensorflow / core / common_runtime / direct_session_test . cc <nl> ppp b / tensorflow / core / common_runtime / direct_session_test . cc <nl> limitations under the License . <nl> # include < vector > <nl> <nl> # include " tensorflow / core / common_runtime / device_factory . h " <nl> + # include " tensorflow / core / common_runtime / device_mgr . h " <nl> # include " tensorflow / core / framework / allocator . h " <nl> # include " tensorflow / core / framework / graph . pb . h " <nl> # include " tensorflow / core / framework / op_kernel . h " <nl> TEST ( DirectSessionTest , TestDirectSessionReset ) { <nl> EXPECT_EQ ( " Cancelled : Session has been closed . " , s . ToString ( ) ) ; <nl> } <nl> <nl> + TEST ( DirectSessionTest , LocalDeviceManager ) { <nl> + SessionOptions options ; <nl> + std : : unique_ptr < Session > session ( NewSession ( options ) ) ; <nl> + <nl> + const DeviceMgr * mgr = nullptr ; <nl> + TF_ASSERT_OK ( session - > LocalDeviceManager ( & mgr ) ) ; <nl> + ASSERT_TRUE ( mgr ! = nullptr ) ; <nl> + EXPECT_GT ( mgr - > ListDevices ( ) . size ( ) , 0 ) ; <nl> + } <nl> + <nl> / / A simple benchmark for the overhead of ` DirectSession : : Run ( ) ` calls <nl> / / with varying numbers of feeds / fetches . <nl> void FeedFetchBenchmarkHelper ( int num_feeds , int iters ) { <nl> mmm a / tensorflow / core / common_runtime / function . cc <nl> ppp b / tensorflow / core / common_runtime / function . cc <nl> class CallOp : public AsyncOpKernel { <nl> done ) ; <nl> FunctionLibraryRuntime : : Options opts ; <nl> opts . step_id = ctx - > step_id ( ) ; <nl> + opts . rendezvous = ctx - > rendezvous ( ) ; <nl> + opts . cancellation_manager = ctx - > cancellation_manager ( ) ; <nl> opts . step_container = ctx - > step_container ( ) ; <nl> opts . stats_collector = ctx - > stats_collector ( ) ; <nl> opts . runner = ctx - > runner ( ) ; <nl> void FunctionLibraryRuntimeImpl : : Run ( const Options & opts , Handle handle , <nl> Executor : : Args exec_args ; <nl> / / Inherit the step_id from the caller . <nl> exec_args . step_id = opts . step_id ; <nl> - exec_args . step_container = opts . step_container ; <nl> - <nl> + exec_args . rendezvous = opts . rendezvous ; <nl> exec_args . stats_collector = opts . stats_collector ; <nl> exec_args . call_frame = frame ; <nl> exec_args . cancellation_manager = opts . cancellation_manager ; <nl> + exec_args . step_container = opts . step_container ; <nl> exec_args . runner = * opts . runner ; <nl> - / / TODO ( zhifengc ) : we can avoid creating rendez here if we know <nl> - / / there is no send / recv nodes in the graph . <nl> - auto * rendez = new IntraProcessRendezvous ( device_mgr_ ) ; <nl> - exec_args . rendezvous = rendez ; <nl> item - > exec - > RunAsync ( <nl> / / Executor args <nl> exec_args , <nl> / / Done callback . <nl> - [ item , frame , rets , rendez , done ] ( const Status & status ) { <nl> + [ item , frame , rets , done ] ( const Status & status ) { <nl> item - > Unref ( ) ; <nl> - rendez - > Unref ( ) ; <nl> Status s = status ; <nl> if ( s . ok ( ) ) { <nl> s = frame - > GetRetvals ( rets ) ; <nl> mmm a / tensorflow / core / common_runtime / memory_types . cc <nl> ppp b / tensorflow / core / common_runtime / memory_types . cc <nl> Status ValidateMemoryTypes ( const DeviceType & device_type , const Graph * g ) { <nl> } ) ; <nl> } <nl> <nl> - static Node * Send ( Graph * g , const string & device_name , bool host , <nl> - const Edge * edge ) { <nl> - const string tensor_name = <nl> - strings : : StrCat ( " edge_ " , edge - > id ( ) , " _ " , edge - > src ( ) - > name ( ) ) ; <nl> + / / Given an Edge whose two endpoints have different memory types and <nl> + / / are gonna to insert a pair of HostSend / Recv or Send / HostRecv nodes , <nl> + / / GetTensorName ( ) returns a unique string that we can use as part of <nl> + / / the rendezvous key . The return string is guaranteed to be unique <nl> + / / within this process . That is sufficient because EnsureMemoryTypes <nl> + / / is only used on a TensorFlow graph that is gonna to be executed in <nl> + / / a single tf device ( hence within a single process ) . <nl> + static string GetTensorName ( const Edge * edge ) { <nl> + static std : : atomic < int64 > counter ( 0 ) ; <nl> + return strings : : StrCat ( " memtype_ " , counter . fetch_add ( 1 ) , " _ " , <nl> + edge - > src ( ) - > name ( ) ) ; <nl> + } <nl> + <nl> + static Node * Send ( Graph * g , const string & tensor_name , <nl> + const string & device_name , bool host , const Edge * edge ) { <nl> Node * ret ; <nl> TF_CHECK_OK ( NodeBuilder ( g - > NewName ( " n " ) , host ? " _HostSend " : " _Send " ) <nl> . Input ( edge - > src ( ) , edge - > src_output ( ) ) <nl> static Node * Send ( Graph * g , const string & device_name , bool host , <nl> . Attr ( " send_device " , device_name ) <nl> . Attr ( " send_device_incarnation " , 0 ) / / Do not care . <nl> . Attr ( " recv_device " , device_name ) <nl> + . Attr ( " _hostmem_sendrecv " , true ) <nl> . Finalize ( g , & ret ) ) ; <nl> return ret ; <nl> } <nl> <nl> - static Node * Recv ( Graph * g , const string & device_name , bool host , <nl> - const Edge * edge ) { <nl> - const string tensor_name = <nl> - strings : : StrCat ( " edge_ " , edge - > id ( ) , " _ " , edge - > src ( ) - > name ( ) ) ; <nl> + static Node * Recv ( Graph * g , const string & tensor_name , <nl> + const string & device_name , bool host , const Edge * edge ) { <nl> Node * ret ; <nl> TF_CHECK_OK ( <nl> NodeBuilder ( g - > NewName ( " n " ) , host ? " _HostRecv " : " _Recv " ) <nl> static Node * Recv ( Graph * g , const string & device_name , bool host , <nl> . Attr ( " send_device " , device_name ) <nl> . Attr ( " send_device_incarnation " , 0 ) <nl> . Attr ( " recv_device " , device_name ) <nl> + . Attr ( " _hostmem_sendrecv " , true ) <nl> . Finalize ( g , & ret ) ) ; <nl> return ret ; <nl> } <nl> Status EnsureMemoryTypes ( const DeviceType & device_type , <nl> Endpoint key { e - > src ( ) - > id ( ) , e - > src_output ( ) } ; <nl> auto iter = recv_nodes . find ( key ) ; <nl> if ( iter = = recv_nodes . end ( ) ) { <nl> - Node * send = Send ( g , device_name , ( item . sm = = HOST_MEMORY ) , e ) ; <nl> - recv = Recv ( g , device_name , ( item . dm = = HOST_MEMORY ) , e ) ; <nl> + const string tensor_name = GetTensorName ( e ) ; <nl> + Node * send = <nl> + Send ( g , tensor_name , device_name , ( item . sm = = HOST_MEMORY ) , e ) ; <nl> + recv = Recv ( g , tensor_name , device_name , ( item . dm = = HOST_MEMORY ) , e ) ; <nl> if ( ! has_ref ) { <nl> / / We only cache if there is no ref is involved . <nl> recv_nodes [ key ] = recv ; <nl> mmm a / tensorflow / core / framework / function . h <nl> ppp b / tensorflow / core / framework / function . h <nl> class CancellationManager ; <nl> class GraphDef ; <nl> class OpKernel ; <nl> class ResourceMgr ; <nl> + class Rendezvous ; <nl> class ScopedStepContainer ; <nl> class StepStatsCollector ; <nl> class Node ; <nl> class FunctionLibraryRuntime { <nl> / / <nl> / / Does not take ownership of " rets " . <nl> struct Options { <nl> - CancellationManager * cancellation_manager = nullptr ; <nl> / / The id of the step that is calling this function . <nl> int64 step_id = 0 ; <nl> - <nl> - / / Per - step container . <nl> + Rendezvous * rendezvous = nullptr ; <nl> + CancellationManager * cancellation_manager = nullptr ; <nl> ScopedStepContainer * step_container = nullptr ; <nl> StepStatsCollector * stats_collector = nullptr ; <nl> <nl> mmm a / tensorflow / core / graph / graph_partition . cc <nl> ppp b / tensorflow / core / graph / graph_partition . cc <nl> Status AddControlEdges ( const PartitionOptions & opts , <nl> return Status : : OK ( ) ; <nl> } <nl> <nl> + / / If ' ndef ' is a Send or Recv , fills its attr send_device_incarnation <nl> + / / if possible . <nl> + void SetIncarnation ( const PartitionOptions & opts , NodeDef * ndef ) { <nl> + StringPiece op ( ndef - > op ( ) ) ; <nl> + if ( op ! = " _Send " & & op ! = " _Recv " ) { <nl> + / / Not related to send / recv . <nl> + return ; <nl> + } <nl> + string send_device ; <nl> + if ( ! GetNodeAttr ( * ndef , " send_device " , & send_device ) . ok ( ) ) { <nl> + / / No known send_device . The runtime will detect it later . <nl> + return ; <nl> + } <nl> + int64 incarnation = opts . get_incarnation ( send_device ) ; <nl> + AddNodeAttr ( " send_device_incarnation " , incarnation , ndef ) ; <nl> + } <nl> + <nl> + / / Sets attribute send_device_incarnation of all Send / Recv nodes in <nl> + / / ' gdef ' , if possible . <nl> + void SetIncarnation ( const PartitionOptions & opts , GraphDef * gdef ) { <nl> + for ( NodeDef & ndef : * gdef - > mutable_node ( ) ) { <nl> + SetIncarnation ( opts , & ndef ) ; <nl> + } <nl> + for ( FunctionDef & fdef : * gdef - > mutable_library ( ) - > mutable_function ( ) ) { <nl> + for ( NodeDef & ndef : * fdef . mutable_node_def ( ) ) { <nl> + SetIncarnation ( opts , & ndef ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> Status Partition ( const PartitionOptions & opts , Graph * g , <nl> std : : unordered_map < string , GraphDef > * partitions ) { <nl> Status status ; <nl> Status Partition ( const PartitionOptions & opts , Graph * g , <nl> } <nl> } <nl> <nl> - / / Set versions and function library <nl> + / / Set versions , function library and send / recv incarnation . <nl> for ( auto & it : * partitions ) { <nl> - it . second . mutable_versions ( ) - > CopyFrom ( g - > versions ( ) ) ; <nl> - * it . second . mutable_library ( ) = g - > flib_def ( ) . ToProto ( ) ; <nl> + GraphDef * gdef = & it . second ; <nl> + * gdef - > mutable_versions ( ) = g - > versions ( ) ; <nl> + * gdef - > mutable_library ( ) = g - > flib_def ( ) . ToProto ( ) ; <nl> + <nl> + / / Traverse the graph to fill every send / recv op ' s incarnation <nl> + / / information . <nl> + SetIncarnation ( opts , gdef ) ; <nl> } <nl> <nl> / / Set the start times for recvs at the very end . <nl> mmm a / tensorflow / core / grappler / clusters / BUILD <nl> ppp b / tensorflow / core / grappler / clusters / BUILD <nl> cc_test ( <nl> deps = [ <nl> " : single_machine " , <nl> " / / tensorflow / cc : cc_ops " , <nl> + " / / tensorflow / cc : resource_variable_ops " , <nl> " / / tensorflow / cc : scope " , <nl> + " / / tensorflow / core : core_cpu_internal " , <nl> " / / tensorflow / core : lib_proto_parsing " , <nl> " / / tensorflow / core : protos_all_cc " , <nl> " / / tensorflow / core : test " , <nl> mmm a / tensorflow / core / grappler / clusters / single_machine . cc <nl> ppp b / tensorflow / core / grappler / clusters / single_machine . cc <nl> SingleMachine : : ~ SingleMachine ( ) { <nl> / / when we delete the session . <nl> thread_pool_ . reset ( ) ; <nl> <nl> - Reset ( options_ , { } ) . IgnoreError ( ) ; <nl> - <nl> CHECK ( already_created ) ; <nl> already_created = false ; <nl> } <nl> Status SingleMachine : : ResetSession ( ) { <nl> / / Make sure the session is properly closed <nl> TF_RETURN_IF_ERROR ( Shutdown ( ) ) ; <nl> <nl> - / / We need to Reset the session to ensure that all the variables are <nl> - / / deleted . But first we need to delete the session since Reset ( ) <nl> - / / deletes some of the containers referenced by the session . <nl> + / / Destroying the object deletes all its varibles as well . This is only true <nl> + / / for DirectSession . <nl> session_ . reset ( ) ; <nl> - TF_RETURN_IF_ERROR ( Reset ( options_ , { } ) ) ; <nl> } <nl> <nl> LOG ( INFO ) < < " Starting new session " ; <nl> mmm a / tensorflow / core / grappler / clusters / single_machine_test . cc <nl> ppp b / tensorflow / core / grappler / clusters / single_machine_test . cc <nl> limitations under the License . <nl> <nl> # include " tensorflow / core / grappler / clusters / single_machine . h " <nl> # include " tensorflow / cc / framework / scope . h " <nl> + # include " tensorflow / cc / ops / resource_variable_ops . h " <nl> # include " tensorflow / cc / ops / standard_ops . h " <nl> + # include " tensorflow / core / common_runtime / device . h " <nl> + # include " tensorflow / core / common_runtime / device_factory . h " <nl> # include " tensorflow / core / framework / cost_graph . pb . h " <nl> # include " tensorflow / core / framework / step_stats . pb . h " <nl> # include " tensorflow / core / framework / tensor_shape . pb . h " <nl> limitations under the License . <nl> # include " tensorflow / core / grappler / utils . h " <nl> # include " tensorflow / core / platform / protobuf . h " <nl> # include " tensorflow / core / platform / test . h " <nl> + # include " tensorflow / core / protobuf / queue_runner . pb . h " <nl> <nl> namespace tensorflow { <nl> namespace grappler { <nl> TEST_F ( SingleMachineTest , InitializationMemory ) { <nl> } <nl> <nl> namespace { <nl> + <nl> template < class T > <nl> inline void SetNodeAttr ( const string & key , const T & value , NodeDef * node ) { <nl> AttrValue attr_value ; <nl> TEST_F ( SingleMachineTest , PersistentMemory ) { <nl> EXPECT_TRUE ( found_hashtable ) ; <nl> } <nl> <nl> + # if defined ( PLATFORM_GOOGLE ) <nl> + namespace { <nl> + <nl> + SessionOptions GetSessionOption ( int num_cpu_cores , int num_gpus ) { <nl> + SessionOptions options ; <nl> + / / Copied from single_machine . h <nl> + ( * options . config . mutable_device_count ( ) ) [ " CPU " ] = 1 ; <nl> + if ( num_gpus > 0 ) { <nl> + ( * options . config . mutable_device_count ( ) ) [ " GPU " ] = num_gpus ; <nl> + } <nl> + CHECK_GE ( num_cpu_cores , 1 ) ; <nl> + options . config . set_intra_op_parallelism_threads ( num_cpu_cores ) ; <nl> + options . config . add_session_inter_op_thread_pool ( ) - > set_num_threads ( <nl> + num_cpu_cores ) ; <nl> + return options ; <nl> + } <nl> + <nl> + Status GetDeviceMemoryStats ( <nl> + const SessionOptions & session_option , <nl> + std : : unordered_map < string , AllocatorStats > * allocator_stats_by_device ) { <nl> + std : : vector < Device * > devices ; <nl> + TF_RETURN_IF_ERROR ( DeviceFactory : : AddDevices ( session_option , <nl> + " " / * name_prefix * / , & devices ) ) ; <nl> + allocator_stats_by_device - > clear ( ) ; <nl> + for ( Device * device : devices ) { <nl> + AllocatorStats stats ; <nl> + auto * allocator = device - > GetAllocator ( AllocatorAttributes ( ) ) ; <nl> + if ( ! allocator - > TracksAllocationSizes ( ) ) { <nl> + return Status ( error : : INVALID_ARGUMENT , <nl> + " Tracking allocation is not enabled . " ) ; <nl> + } <nl> + allocator - > GetStats ( & stats ) ; <nl> + ( * allocator_stats_by_device ) [ device - > name ( ) ] = stats ; <nl> + } <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> + TEST_F ( SingleMachineTest , ReleaseMemoryAfterDestruction ) { <nl> + tensorflow : : Scope s = tensorflow : : Scope : : NewRootScope ( ) ; <nl> + <nl> + / / Add a variable and initializer . <nl> + Output a = ops : : Variable ( s . WithOpName ( " a " ) , TensorShape ( { 128 , 256 } ) , <nl> + DataType : : DT_FLOAT ) ; <nl> + Output a_init = <nl> + ops : : RandomNormal ( s . WithOpName ( " a / init " ) , { 128 , 256 } , DataType : : DT_FLOAT ) ; <nl> + Output a_init_assign = ops : : Assign ( s . WithOpName ( " a / init / assign " ) , a , a_init ) ; <nl> + <nl> + / / Add a resource variable . <nl> + Output b = <nl> + ops : : VarHandleOp ( s . WithOpName ( " b " ) , DataType : : DT_FLOAT , { 256 , 512 } ) ; <nl> + Output b_read = <nl> + ops : : ReadVariableOp ( s . WithOpName ( " b / read " ) , b , DataType : : DT_FLOAT ) ; <nl> + Output b_init = <nl> + ops : : RandomNormal ( s . WithOpName ( " b / init " ) , { 256 , 512 } , DataType : : DT_FLOAT ) ; <nl> + auto b_init_assign = <nl> + ops : : AssignVariableOp ( s . WithOpName ( " b / init / assign " ) , b , b_init ) ; <nl> + <nl> + / / Add a queue . <nl> + ops : : FIFOQueue queue ( s . WithOpName ( " queue " ) , { DataType : : DT_STRING } ) ; <nl> + Output some_string = <nl> + ops : : Const ( s . WithOpName ( " some_string " ) , string ( " nothing " ) ) ; <nl> + ops : : QueueEnqueue enqueue ( s . WithOpName ( " enqueue " ) , queue , { some_string } ) ; <nl> + ops : : QueueDequeue dequeue ( s . WithOpName ( " dequeue " ) , queue , <nl> + { DataType : : DT_STRING } ) ; <nl> + <nl> + / / Add a IdentityReader . <nl> + ops : : IdentityReader reader ( s . WithOpName ( " identity_reader " ) ) ; <nl> + ops : : ReaderRead read ( s . WithOpName ( " read_from_queue " ) , reader , queue ) ; <nl> + <nl> + Output var_mul = ops : : MatMul ( s . WithOpName ( " var_matmul " ) , a , b_read ) ; <nl> + <nl> + GrapplerItem item ; <nl> + TF_CHECK_OK ( s . ToGraphDef ( & item . graph ) ) ; <nl> + <nl> + QueueRunnerDef queue_runner ; <nl> + queue_runner . set_queue_name ( " queue " ) ; <nl> + * queue_runner . add_enqueue_op_name ( ) = " enqueue " ; <nl> + item . queue_runners . push_back ( queue_runner ) ; <nl> + <nl> + item . init_ops . push_back ( " a / init / assign " ) ; <nl> + item . init_ops . push_back ( " b / init / assign " ) ; <nl> + item . fetch . push_back ( " var_matmul " ) ; <nl> + item . fetch . push_back ( " dequeue " ) ; <nl> + <nl> + / / Run the graph <nl> + TF_CHECK_OK ( cluster_ - > Initialize ( item ) ) ; <nl> + EnableCPUAllocatorStats ( true ) ; <nl> + <nl> + SessionOptions options = <nl> + GetSessionOption ( 3 / * cpu cores * / , 0 / * num gpus * / ) ; <nl> + std : : unordered_map < string , AllocatorStats > device_memory_before ; <nl> + TF_CHECK_OK ( GetDeviceMemoryStats ( options , & device_memory_before ) ) ; <nl> + EXPECT_EQ ( device_memory_before . size ( ) , 1 ) ; <nl> + <nl> + RunMetadata metadata ; <nl> + TF_CHECK_OK ( cluster_ - > Run ( item . graph , item . feed , item . fetch , & metadata ) ) ; <nl> + <nl> + / / Check there is memory that is not released . <nl> + std : : unordered_map < string , AllocatorStats > device_memory ; <nl> + TF_CHECK_OK ( GetDeviceMemoryStats ( options , & device_memory ) ) ; <nl> + EXPECT_EQ ( device_memory . size ( ) , 1 ) ; <nl> + EXPECT_GT ( device_memory . begin ( ) - > second . bytes_in_use , 0 ) ; <nl> + <nl> + / / Reset cluster_ would release all memory . <nl> + cluster_ . reset ( ) ; <nl> + std : : unordered_map < string , AllocatorStats > device_memory_after ; <nl> + TF_CHECK_OK ( GetDeviceMemoryStats ( options , & device_memory_after ) ) ; <nl> + <nl> + / / Check memory used by resources are released after cluster destruction . <nl> + EXPECT_EQ ( device_memory_before . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( device_memory_after . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( device_memory_before . begin ( ) - > second . bytes_in_use , 0 ) ; <nl> + EXPECT_EQ ( device_memory_after . begin ( ) - > second . bytes_in_use , 0 ) ; <nl> + } <nl> + # endif <nl> + <nl> } / / namespace <nl> } / / namespace grappler <nl> } / / namespace tensorflow <nl> mmm a / tensorflow / core / grappler / grappler_item_builder . cc <nl> ppp b / tensorflow / core / grappler / grappler_item_builder . cc <nl> Status OptimizeGraph ( const GraphDef & graph_def , GraphDef * output_graph_def , <nl> <nl> / / Inline all functions . <nl> GraphDef inlined_graph_def ( graph_def ) ; <nl> - / / Populate default attrs to the NodeDefs in the GraphDef , which is required <nl> - / / by inlining code . <nl> - TF_RETURN_IF_ERROR ( <nl> - AddDefaultAttrsToGraphDef ( & inlined_graph_def , * OpRegistry : : Global ( ) , 0 ) ) ; <nl> <nl> for ( int i = 0 ; i < inlined_graph_def . library ( ) . function ( ) . size ( ) ; i + + ) { <nl> FunctionDef * fdef = <nl> Status OptimizeGraph ( const GraphDef & graph_def , GraphDef * output_graph_def , <nl> graph_ctor_opts . allow_internal_ops = true ; <nl> graph_ctor_opts . expect_device_spec = false ; <nl> std : : unique_ptr < Graph > graphptr ( new Graph ( function_library ) ) ; <nl> + / / Populate default attrs to the NodeDefs in the GraphDef . <nl> + TF_RETURN_IF_ERROR ( AddDefaultAttrsToGraphDef ( & inlined_graph_def , <nl> + * graphptr - > op_registry ( ) , 0 ) ) ; <nl> + <nl> TF_RETURN_IF_ERROR ( ConvertGraphDefToGraph ( graph_ctor_opts , inlined_graph_def , <nl> graphptr . get ( ) ) ) ; <nl> <nl> mmm a / tensorflow / core / grappler / inputs / trivial_test_graph_input_yielder . cc <nl> ppp b / tensorflow / core / grappler / inputs / trivial_test_graph_input_yielder . cc <nl> GraphDef CreateGraphDef ( int num_stages , int width , int tensor_size , <nl> for ( int i = 0 ; i < num_stages ; i + + ) { <nl> std : : vector < Output > this_stage ; <nl> for ( int j = 0 ; j < width ; j + + ) { <nl> - Output combine = AddN ( <nl> - s . WithDevice ( device_names [ use_multiple_devices ? j : 0 ] ) , last_stage ) ; <nl> - this_stage . push_back ( combine ) ; <nl> + if ( last_stage . size ( ) = = 1 ) { <nl> + Output unary_op = <nl> + Square ( s . WithDevice ( device_names [ use_multiple_devices ? j : 0 ] ) , <nl> + last_stage [ 0 ] ) ; <nl> + this_stage . push_back ( unary_op ) ; <nl> + } else { <nl> + Output combine = <nl> + AddN ( s . WithDevice ( device_names [ use_multiple_devices ? j : 0 ] ) , <nl> + last_stage ) ; <nl> + this_stage . push_back ( combine ) ; <nl> + } <nl> } <nl> last_stage = this_stage ; <nl> } <nl> mmm a / tensorflow / core / grappler / op_types . cc <nl> ppp b / tensorflow / core / grappler / op_types . cc <nl> limitations under the License . <nl> namespace tensorflow { <nl> namespace grappler { <nl> <nl> + bool IsAddN ( const NodeDef & node ) { <nl> + const auto op = node . op ( ) ; <nl> + return op = = " AddN " ; <nl> + } <nl> + <nl> bool IsConcat ( const NodeDef & node ) { <nl> const auto op = node . op ( ) ; <nl> return op = = " Concat " | | op = = " ConcatV2 " ; <nl> mmm a / tensorflow / core / grappler / op_types . h <nl> ppp b / tensorflow / core / grappler / op_types . h <nl> limitations under the License . <nl> namespace tensorflow { <nl> namespace grappler { <nl> <nl> + bool IsAddN ( const NodeDef & node ) ; <nl> bool IsConcat ( const NodeDef & node ) ; <nl> bool IsConstant ( const NodeDef & node ) ; <nl> bool IsDequeueOp ( const NodeDef & node ) ; <nl> mmm a / tensorflow / core / grappler / optimizers / model_pruner . cc <nl> ppp b / tensorflow / core / grappler / optimizers / model_pruner . cc <nl> limitations under the License . <nl> namespace tensorflow { <nl> namespace grappler { <nl> <nl> + int NumNonControlInputs ( const NodeDef & node ) { <nl> + int num_inputs = node . input_size ( ) ; <nl> + for ( int i = 0 ; i < node . input_size ( ) ; + + i ) { <nl> + if ( ! node . input ( i ) . empty ( ) & & node . input ( i ) [ 0 ] = = ' ^ ' ) { <nl> + num_inputs - - ; <nl> + } <nl> + } <nl> + return num_inputs ; <nl> + } <nl> + <nl> + bool IsTrivialOp ( const NodeDef & node ) { <nl> + / / Remove the stop gradient nodes since they serve no purpose once the graph <nl> + / / is built . Also remove Identity ops . <nl> + if ( IsStopGradient ( node ) | | IsIdentity ( node ) ) { <nl> + return true ; <nl> + } <nl> + if ( IsAddN ( node ) & & NumNonControlInputs ( node ) < = 1 ) { <nl> + return true ; <nl> + } <nl> + <nl> + return false ; <nl> + } <nl> + <nl> Status ModelPruner : : Optimize ( Cluster * cluster , const GrapplerItem & item , <nl> GraphDef * pruned_graph ) { <nl> GraphRewriter rewriter ( item ) ; <nl> Status ModelPruner : : Optimize ( Cluster * cluster , const GrapplerItem & item , <nl> <nl> std : : unordered_set < const NodeDef * > nodes_to_delete ; <nl> for ( auto & node : item . graph . node ( ) ) { <nl> - / / Remove the stop gradient nodes since they serve no purpose once the graph <nl> - / / is built . Also remove Identity ops . <nl> - if ( ! IsStopGradient ( node ) & & ! IsIdentity ( node ) ) { <nl> + if ( ! IsTrivialOp ( node ) ) { <nl> continue ; <nl> } <nl> / / Don ' t remove nodes that must be preserved . <nl> mmm a / tensorflow / core / grappler / optimizers / model_pruner_test . cc <nl> ppp b / tensorflow / core / grappler / optimizers / model_pruner_test . cc <nl> TEST_F ( ModelPrunerTest , StopGradientPruning ) { <nl> tensorflow : : Scope s = tensorflow : : Scope : : NewRootScope ( ) ; <nl> <nl> Output a = ops : : Const ( s . WithOpName ( " a " ) , 0 . 0f , { 10 , 10 } ) ; <nl> - Output b = ops : : AddN ( s . WithOpName ( " b " ) , { a } ) ; <nl> + Output b = ops : : Sqrt ( s . WithOpName ( " b " ) , { a } ) ; <nl> Output c = ops : : StopGradient ( s . WithOpName ( " c " ) , b ) ; <nl> Output d = ops : : StopGradient ( s . WithOpName ( " d " ) , c ) ; <nl> - Output e = ops : : AddN ( s . WithOpName ( " e " ) , { d } ) ; <nl> + Output e = ops : : Sqrt ( s . WithOpName ( " e " ) , { d } ) ; <nl> <nl> GrapplerItem item ; <nl> TF_CHECK_OK ( s . ToGraphDef ( & item . graph ) ) ; <nl> TEST_F ( ModelPrunerTest , IdentityPruning ) { <nl> tensorflow : : Scope s = tensorflow : : Scope : : NewRootScope ( ) ; <nl> <nl> Output a = ops : : Const ( s . WithOpName ( " a " ) , 0 . 0f , { 10 , 10 } ) ; <nl> - Output b = ops : : AddN ( s . WithOpName ( " b " ) , { a } ) ; <nl> + Output b = ops : : Sqrt ( s . WithOpName ( " b " ) , { a } ) ; <nl> Output c = ops : : Identity ( s . WithOpName ( " c " ) , b ) ; <nl> Output d = ops : : Identity ( s . WithOpName ( " d " ) , c ) ; <nl> - Output e = ops : : AddN ( s . WithOpName ( " e " ) , { d } ) ; <nl> + Output e = ops : : Sqrt ( s . WithOpName ( " e " ) , { d } ) ; <nl> <nl> GrapplerItem item ; <nl> TF_CHECK_OK ( s . ToGraphDef ( & item . graph ) ) ; <nl> TEST_F ( ModelPrunerTest , IdentityPruning ) { <nl> EXPECT_EQ ( NodeName ( b . name ( ) ) , new_c . input ( 0 ) ) ; <nl> } <nl> <nl> - TEST_F ( ModelPrunerTest , PruningSkipsCtrlDependencies ) { <nl> + TEST_F ( ModelPrunerTest , NoOpPruning ) { <nl> / / Build a simple graph with a few trivially prunable ops . <nl> tensorflow : : Scope s = tensorflow : : Scope : : NewRootScope ( ) ; <nl> <nl> Output a = ops : : Const ( s . WithOpName ( " a " ) , 0 . 0f , { 10 , 10 } ) ; <nl> Output b = ops : : AddN ( s . WithOpName ( " b " ) , { a } ) ; <nl> + Output c = ops : : AddN ( s . WithOpName ( " c " ) , { b } ) ; <nl> + Output d = ops : : AddN ( s . WithOpName ( " d " ) . WithControlDependencies ( b ) , { c } ) ; <nl> + Output e = ops : : AddN ( s . WithOpName ( " e " ) , { d } ) ; <nl> + <nl> + GrapplerItem item ; <nl> + TF_CHECK_OK ( s . ToGraphDef ( & item . graph ) ) ; <nl> + <nl> + ModelPruner pruner ; <nl> + GraphDef output ; <nl> + Status status = pruner . Optimize ( nullptr , item , & output ) ; <nl> + TF_EXPECT_OK ( status ) ; <nl> + <nl> + EXPECT_EQ ( 5 , output . node_size ( ) ) ; <nl> + const NodeDef & new_a = output . node ( 0 ) ; <nl> + EXPECT_EQ ( NodeName ( a . name ( ) ) , new_a . name ( ) ) ; <nl> + const NodeDef & new_b = output . node ( 1 ) ; <nl> + EXPECT_EQ ( NodeName ( b . name ( ) ) , new_b . name ( ) ) ; <nl> + const NodeDef & new_c = output . node ( 2 ) ; <nl> + EXPECT_EQ ( NodeName ( c . name ( ) ) , new_c . name ( ) ) ; <nl> + const NodeDef & new_d = output . node ( 3 ) ; <nl> + EXPECT_EQ ( NodeName ( d . name ( ) ) , new_d . name ( ) ) ; <nl> + const NodeDef & new_e = output . node ( 4 ) ; <nl> + EXPECT_EQ ( NodeName ( e . name ( ) ) , new_e . name ( ) ) ; <nl> + <nl> + EXPECT_EQ ( 1 , new_e . input_size ( ) ) ; <nl> + EXPECT_EQ ( NodeName ( d . name ( ) ) , new_e . input ( 0 ) ) ; <nl> + EXPECT_EQ ( 2 , new_d . input_size ( ) ) ; <nl> + EXPECT_EQ ( NodeName ( b . name ( ) ) , new_d . input ( 0 ) ) ; <nl> + EXPECT_EQ ( 1 , new_c . input_size ( ) ) ; <nl> + EXPECT_EQ ( NodeName ( b . name ( ) ) , new_c . input ( 0 ) ) ; <nl> + } <nl> + <nl> + TEST_F ( ModelPrunerTest , PruningSkipsCtrlDependencies ) { <nl> + / / Build a simple graph with a few trivially prunable ops . <nl> + tensorflow : : Scope s = tensorflow : : Scope : : NewRootScope ( ) ; <nl> + <nl> + Output a = ops : : Const ( s . WithOpName ( " a " ) , 0 . 0f , { 10 , 10 } ) ; <nl> + Output b = ops : : Sqrt ( s . WithOpName ( " b " ) , { a } ) ; <nl> Output c = ops : : Identity ( s . WithOpName ( " c " ) , b ) ; <nl> Output d = ops : : Identity ( s . WithOpName ( " d " ) , c ) ; <nl> - Output e = ops : : AddN ( s . WithOpName ( " e " ) . WithControlDependencies ( c ) , { d } ) ; <nl> + Output e = ops : : Sqrt ( s . WithOpName ( " e " ) . WithControlDependencies ( c ) , { d } ) ; <nl> <nl> GrapplerItem item ; <nl> TF_CHECK_OK ( s . ToGraphDef ( & item . graph ) ) ; <nl> TEST_F ( ModelPrunerTest , PruningPerservesCtrlDependencies ) { <nl> tensorflow : : Scope s = tensorflow : : Scope : : NewRootScope ( ) ; <nl> <nl> Output a = ops : : Const ( s . WithOpName ( " a " ) , 0 . 0f , { 10 , 10 } ) ; <nl> - Output b = ops : : AddN ( s . WithOpName ( " b " ) , { a } ) ; <nl> - Output c = ops : : AddN ( s . WithOpName ( " c " ) , { a } ) ; <nl> + Output b = ops : : Sqrt ( s . WithOpName ( " b " ) , { a } ) ; <nl> + Output c = ops : : Sqrt ( s . WithOpName ( " c " ) , { a } ) ; <nl> Output d = ops : : Identity ( s . WithOpName ( " d " ) , c ) ; <nl> Output e = ops : : Identity ( s . WithOpName ( " e " ) , d ) ; <nl> - Output f = ops : : AddN ( s . WithOpName ( " f " ) , { e } ) ; <nl> + Output f = ops : : Sqrt ( s . WithOpName ( " f " ) , { e } ) ; <nl> <nl> GrapplerItem item ; <nl> TF_CHECK_OK ( s . ToGraphDef ( & item . graph ) ) ; <nl> TEST_F ( ModelPrunerTest , PruningPerservesFetch ) { <nl> tensorflow : : Scope s = tensorflow : : Scope : : NewRootScope ( ) ; <nl> <nl> Output a = ops : : Const ( s . WithOpName ( " a " ) , 0 . 0f , { 10 , 10 } ) ; <nl> - Output b = ops : : AddN ( s . WithOpName ( " b " ) , { a } ) ; <nl> + Output b = ops : : Sqrt ( s . WithOpName ( " b " ) , { a } ) ; <nl> Output c = ops : : Identity ( s . WithOpName ( " c " ) , b ) ; <nl> <nl> GrapplerItem item ; <nl> TEST_F ( ModelPrunerTest , PruningPerservesCrossDeviceIdentity ) { <nl> <nl> / / Node i1 should be preserved . <nl> Output i1 = ops : : Identity ( s . WithOpName ( " i1 " ) . WithDevice ( " / gpu : 0 " ) , c ) ; <nl> - Output a1 = ops : : AddN ( s . WithOpName ( " a1 " ) . WithDevice ( " / gpu : 0 " ) , { i1 } ) ; <nl> - Output a2 = ops : : AddN ( s . WithOpName ( " a2 " ) . WithDevice ( " / gpu : 0 " ) , { i1 } ) ; <nl> + Output a1 = ops : : Sqrt ( s . WithOpName ( " a1 " ) . WithDevice ( " / gpu : 0 " ) , { i1 } ) ; <nl> + Output a2 = ops : : Sqrt ( s . WithOpName ( " a2 " ) . WithDevice ( " / gpu : 0 " ) , { i1 } ) ; <nl> <nl> / / Node i2 should be pruned since it resides on the sender ' s device . <nl> Output i2 = ops : : Identity ( s . WithOpName ( " i2 " ) . WithDevice ( " / cpu : 0 " ) , c ) ; <nl> - Output a3 = ops : : AddN ( s . WithOpName ( " a3 " ) . WithDevice ( " / gpu : 0 " ) , { i2 } ) ; <nl> - Output a4 = ops : : AddN ( s . WithOpName ( " a4 " ) . WithDevice ( " / gpu : 0 " ) , { i2 } ) ; <nl> + Output a3 = ops : : Sqrt ( s . WithOpName ( " a3 " ) . WithDevice ( " / gpu : 0 " ) , { i2 } ) ; <nl> + Output a4 = ops : : Sqrt ( s . WithOpName ( " a4 " ) . WithDevice ( " / gpu : 0 " ) , { i2 } ) ; <nl> <nl> GrapplerItem item ; <nl> TF_CHECK_OK ( s . ToGraphDef ( & item . graph ) ) ; <nl> mmm a / tensorflow / core / kernels / function_ops . cc <nl> ppp b / tensorflow / core / kernels / function_ops . cc <nl> class SymbolicGradientOp : public AsyncOpKernel { <nl> <nl> FunctionLibraryRuntime : : Options opts ; <nl> opts . step_id = ctx - > step_id ( ) ; <nl> + opts . rendezvous = ctx - > rendezvous ( ) ; <nl> + opts . cancellation_manager = ctx - > cancellation_manager ( ) ; <nl> opts . runner = ctx - > runner ( ) ; <nl> std : : vector < Tensor > args ; <nl> args . reserve ( ctx - > num_inputs ( ) ) ; <nl> mmm a / tensorflow / core / kernels / lookup_table_op . cc <nl> ppp b / tensorflow / core / kernels / lookup_table_op . cc <nl> class MutableHashTableOfScalars final : public LookupInterface { <nl> <nl> TensorShape value_shape ( ) const override { return TensorShape ( ) ; } <nl> <nl> + int64 MemoryUsed ( ) const override { <nl> + int64 ret = 0 ; <nl> + mutex_lock l ( mu_ ) ; <nl> + for ( unsigned i = 0 ; i < table_ . bucket_count ( ) ; + + i ) { <nl> + size_t bucket_size = table_ . bucket_size ( i ) ; <nl> + if ( bucket_size = = 0 ) { <nl> + ret + + ; <nl> + } else { <nl> + ret + = bucket_size ; <nl> + } <nl> + } <nl> + return sizeof ( MutableHashTableOfScalars ) + ret ; <nl> + } <nl> + <nl> private : <nl> / / TODO ( andreasst ) : consider using a read / write lock or a concurrent map <nl> mutable mutex mu_ ; <nl> class MutableHashTableOfTensors final : public LookupInterface { <nl> <nl> TensorShape value_shape ( ) const override { return value_shape_ ; } <nl> <nl> + int64 MemoryUsed ( ) const override { <nl> + int64 ret = 0 ; <nl> + mutex_lock l ( mu_ ) ; <nl> + for ( unsigned i = 0 ; i < table_ . bucket_count ( ) ; + + i ) { <nl> + size_t bucket_size = table_ . bucket_size ( i ) ; <nl> + if ( bucket_size = = 0 ) { <nl> + ret + + ; <nl> + } else { <nl> + ret + = bucket_size ; <nl> + } <nl> + } <nl> + return sizeof ( MutableHashTableOfTensors ) + ret ; <nl> + } <nl> + <nl> private : <nl> TensorShape value_shape_ ; <nl> / / TODO ( andreasst ) : consider using a read / write lock or a concurrent map <nl> class MutableDenseHashTable final : public LookupInterface { <nl> <nl> TensorShape value_shape ( ) const override { return value_shape_ ; } <nl> <nl> + int64 MemoryUsed ( ) const override { <nl> + mutex_lock l ( mu_ ) ; <nl> + return sizeof ( MutableDenseHashTable ) + key_buckets_ . AllocatedBytes ( ) + <nl> + value_buckets_ . AllocatedBytes ( ) + empty_key_ . AllocatedBytes ( ) ; <nl> + } <nl> + <nl> private : <nl> Status DoInsert ( OpKernelContext * ctx , const Tensor & key , const Tensor & value , <nl> bool ignore_empty_key ) EXCLUSIVE_LOCKS_REQUIRED ( mu_ ) { <nl> mmm a / tensorflow / core / kernels / sendrecv_ops . cc <nl> ppp b / tensorflow / core / kernels / sendrecv_ops . cc <nl> static void GetRendezvousKey ( const string & key_prefix , <nl> frame_iter . iter_id ) ; <nl> } <nl> <nl> + static FrameAndIter GetFrameAndIter ( OpKernelContext * ctx , <nl> + bool hostmem_sendrecv ) { <nl> + if ( hostmem_sendrecv & & ctx - > call_frame ( ) ! = nullptr ) { <nl> + / / Host memory send / recv pairs are added by <nl> + / / common_runtime / memory_types . cc . When the pair of nodes are <nl> + / / added inside a function , we need to use the function call frame <nl> + / / to formulate the unique rendezvous key . <nl> + return FrameAndIter ( reinterpret_cast < uint64 > ( ctx - > call_frame ( ) ) , 0 ) ; <nl> + } else { <nl> + return ctx - > frame_iter ( ) ; <nl> + } <nl> + } <nl> + <nl> SendOp : : SendOp ( OpKernelConstruction * ctx ) : OpKernel ( ctx ) { <nl> string send_device ; <nl> OP_REQUIRES_OK ( ctx , ctx - > GetAttr ( " send_device " , & send_device ) ) ; <nl> SendOp : : SendOp ( OpKernelConstruction * ctx ) : OpKernel ( ctx ) { <nl> / / proactively cache the rendezvous key for the top - level . <nl> GetRendezvousKey ( key_prefix_ , { 0 , 0 } , & parsed_key_ . buf_ ) ; <nl> OP_REQUIRES_OK ( ctx , Rendezvous : : ParseKey ( parsed_key_ . buf_ , & parsed_key_ ) ) ; <nl> + if ( ! ctx - > GetAttr ( " _hostmem_sendrecv " , & hostmem_sendrecv_ ) . ok ( ) ) { <nl> + hostmem_sendrecv_ = false ; <nl> + } <nl> } <nl> <nl> void SendOp : : Compute ( OpKernelContext * ctx ) { <nl> void SendOp : : Compute ( OpKernelContext * ctx ) { <nl> args . device_context = ctx - > op_device_context ( ) ; <nl> args . alloc_attrs = ctx - > input_alloc_attr ( 0 ) ; <nl> <nl> - if ( ctx - > frame_iter ( ) = = FrameAndIter ( 0 , 0 ) ) { <nl> + FrameAndIter frame_iter = GetFrameAndIter ( ctx , hostmem_sendrecv_ ) ; <nl> + if ( frame_iter = = FrameAndIter ( 0 , 0 ) ) { <nl> / / Use the cached rendezvous key . <nl> VLOG ( 2 ) < < " Send " < < parsed_key_ . buf_ ; <nl> OP_REQUIRES_OK ( ctx , <nl> void SendOp : : Compute ( OpKernelContext * ctx ) { <nl> ctx - > is_input_dead ( ) ) ) ; <nl> } else { <nl> Rendezvous : : ParsedKey in_loop_parsed ; <nl> - GetRendezvousKey ( key_prefix_ , ctx - > frame_iter ( ) , & in_loop_parsed . buf_ ) ; <nl> + GetRendezvousKey ( key_prefix_ , frame_iter , & in_loop_parsed . buf_ ) ; <nl> VLOG ( 2 ) < < " Send " < < in_loop_parsed . buf_ ; <nl> OP_REQUIRES_OK ( ctx , <nl> Rendezvous : : ParseKey ( in_loop_parsed . buf_ , & in_loop_parsed ) ) ; <nl> RecvOp : : RecvOp ( OpKernelConstruction * ctx ) : AsyncOpKernel ( ctx ) { <nl> / / proactively cache the rendezvous key for the top - level . <nl> GetRendezvousKey ( key_prefix_ , { 0 , 0 } , & parsed_key_ . buf_ ) ; <nl> OP_REQUIRES_OK ( ctx , Rendezvous : : ParseKey ( parsed_key_ . buf_ , & parsed_key_ ) ) ; <nl> + if ( ! ctx - > GetAttr ( " _hostmem_sendrecv " , & hostmem_sendrecv_ ) . ok ( ) ) { <nl> + hostmem_sendrecv_ = false ; <nl> + } <nl> } <nl> <nl> void RecvOp : : ComputeAsync ( OpKernelContext * ctx , DoneCallback done ) { <nl> void RecvOp : : ComputeAsync ( OpKernelContext * ctx , DoneCallback done ) { <nl> } , <nl> std : : move ( done ) , _1 , _2 , _3 , _4 , _5 ) ; <nl> <nl> - if ( ctx - > frame_iter ( ) = = FrameAndIter ( 0 , 0 ) ) { <nl> + FrameAndIter frame_iter = GetFrameAndIter ( ctx , hostmem_sendrecv_ ) ; <nl> + if ( frame_iter = = FrameAndIter ( 0 , 0 ) ) { <nl> VLOG ( 2 ) < < " Recv " < < parsed_key_ . buf_ ; <nl> ctx - > rendezvous ( ) - > RecvAsync ( parsed_key_ , args , std : : move ( done_cb ) ) ; <nl> } else { <nl> Rendezvous : : ParsedKey in_loop_parsed ; <nl> - GetRendezvousKey ( key_prefix_ , ctx - > frame_iter ( ) , & in_loop_parsed . buf_ ) ; <nl> + GetRendezvousKey ( key_prefix_ , frame_iter , & in_loop_parsed . buf_ ) ; <nl> VLOG ( 2 ) < < " Recv " < < in_loop_parsed . buf_ ; <nl> OP_REQUIRES_OK_ASYNC ( <nl> ctx , Rendezvous : : ParseKey ( in_loop_parsed . buf_ , & in_loop_parsed ) , done ) ; <nl> mmm a / tensorflow / core / kernels / sendrecv_ops . h <nl> ppp b / tensorflow / core / kernels / sendrecv_ops . h <nl> class SendOp : public OpKernel { <nl> private : <nl> string key_prefix_ ; <nl> Rendezvous : : ParsedKey parsed_key_ ; <nl> + bool hostmem_sendrecv_ ; <nl> <nl> TF_DISALLOW_COPY_AND_ASSIGN ( SendOp ) ; <nl> } ; <nl> class RecvOp : public AsyncOpKernel { <nl> private : <nl> string key_prefix_ ; <nl> Rendezvous : : ParsedKey parsed_key_ ; <nl> + bool hostmem_sendrecv_ ; <nl> <nl> TF_DISALLOW_COPY_AND_ASSIGN ( RecvOp ) ; <nl> } ; <nl> mmm a / tensorflow / core / public / session . h <nl> ppp b / tensorflow / core / public / session . h <nl> limitations under the License . <nl> # include " tensorflow / core / public / session_options . h " <nl> <nl> namespace tensorflow { <nl> + class DeviceMgr ; <nl> <nl> / / / \ brief A Session instance lets a caller drive a TensorFlow graph <nl> / / / computation . <nl> class Session { <nl> / / / * response . This API is optional . If it is unimplemented , Status will <nl> / / / return a corresponding error message , and * response will be unmodified . <nl> virtual Status ListDevices ( std : : vector < DeviceAttributes > * response ) = 0 ; <nl> + <nl> / / / \ brief Closes this session . <nl> / / / <nl> / / / Closing a session releases the resources used by this session <nl> / / / on the TensorFlow runtime ( specified during session creation by <nl> / / / the ` SessionOptions : : target ` field ) . <nl> virtual Status Close ( ) = 0 ; <nl> + <nl> + / / NOTE ( ashankar ) : As of July 2017 , this is was a method added to <nl> + / / faciliate some experimentation . Reconsider / re - evaluate after <nl> + / / September 2017 . <nl> + / / <nl> + / / Sets ` * output ` to the ` DeviceMgr ` that owns accessible devices in the <nl> + / / address - space of the caller . <nl> + virtual Status LocalDeviceManager ( const DeviceMgr * * output ) { <nl> + return errors : : Unimplemented ( <nl> + " LocalDeviceManager is not supported for this session . " ) ; <nl> + } <nl> } ; <nl> <nl> / / / \ brief Create a new session with the given options . <nl> new file mode 100644 <nl> index 0000000000000 . . a5724ea294e1b <nl> mmm / dev / null <nl> ppp b / tensorflow / docs_src / programmers_guide / estimators . md <nl> <nl> + # Estimators <nl> + <nl> + This document introduces * * Estimators * * - - a high - level TensorFlow API that <nl> + greatly simplifies machine learning programming . Estimators encapsulate <nl> + the following actions : <nl> + <nl> + * training <nl> + * evaluation <nl> + * prediction <nl> + * export for serving <nl> + <nl> + You may either use the pre - made Estimators we provide or write your <nl> + own custom Estimators . All Estimators - - whether pre - made or custom - - are <nl> + classes based on the ` tf . estimator . Estimator ` class . <nl> + <nl> + Note : TensorFlow also provides an Estimator class at <nl> + ` tf . contrib . learn . Estimator ` , which you should not use . < / aside > <nl> + <nl> + <nl> + # # Advantages of Estimators <nl> + <nl> + Estimators provide the following benefits : <nl> + <nl> + * You can run Estimators - based models on a local host or on a <nl> + distributed multi - server environment without changing your model . <nl> + Furthermore , you can run Estimators - based models on CPUs , GPUs , <nl> + or TPUs without recoding your model . <nl> + * Estimators simplify sharing implementations between model developers . <nl> + * You can develop a state of the art model with high - level intuitive code , <nl> + In short , it is generally much easier to create models with Estimators <nl> + than with the low - level TensorFlow APIs . <nl> + * Estimators are themselves built on tf . layers , which <nl> + simplifies customization . <nl> + * Estimators build the graph for you . In other words , you don ' t have to <nl> + build the graph . <nl> + * Estimators provide a safe distributed training loop that controls how and <nl> + when to : <nl> + * build the graph <nl> + * initialize variables <nl> + * start queues <nl> + * handle exceptions <nl> + * create checkpoint files and recover from failures <nl> + * save summaries for TensorBoard <nl> + <nl> + When writing an application with Estimators , you must separate the data input <nl> + pipeline from the model . This separation simplifies experiments with <nl> + different data sets . <nl> + <nl> + <nl> + # # Pre - made Estimators <nl> + <nl> + Pre - made Estimators enable you to work at a much higher conceptual level <nl> + than the base TensorFlow APIs . You no longer have to worry about creating <nl> + the computational graph or sessions since Estimators handle all <nl> + the " plumbing " for you . That is , pre - made Estimators create and manage <nl> + ` Graph ` and ` Session ` objects for you . Furthermore , pre - made Estimators <nl> + let you experiment with different model architectures by making only minimal <nl> + code changes . ` DNNClassifier ` , for example , is a pre - made Estimator class that <nl> + trains classification models through dense , feed - forward neural networks . <nl> + <nl> + <nl> + # # # Structure of a pre - made Estimators program <nl> + <nl> + A TensorFlow program relying on a pre - made Estimator typically consists <nl> + of the following four steps : <nl> + <nl> + 1 . * * Write one or more dataset importing functions . * * For example , you might <nl> + create one function to import the training set and another function to <nl> + import the test set . Each dataset importing function must return two <nl> + objects : <nl> + <nl> + * a dictionary in which the keys are feature column names and the <nl> + values are Tensors ( or SparseTensors ) containing the corresponding <nl> + feature data <nl> + * a Tensor containing one or more labels <nl> + <nl> + For example , the following code illustrates the basic skeleton for <nl> + an input function : <nl> + <nl> + def input_fn ( dataset ) : <nl> + . . . # manipulate dataset , extracting feature names and the label <nl> + return feature_dict , label <nl> + <nl> + See @ { $ datasets $ Using the ` Dataset ` API for TensorFlow Input Pipelines } <nl> + for full details . ) <nl> + <nl> + 2 . * * Define the feature columns . * * Each @ { tf . feature_column } <nl> + identifies a feature name , its type , and any input pre - processing . <nl> + For example , the following snippet creates three feature <nl> + columns that hold integer or floating - point data . The first two <nl> + feature columns simply identify the feature ' s name and type . The <nl> + third feature column also specifies a lambda the program will invoke <nl> + to scale the raw data : <nl> + <nl> + # Define three numeric feature columns . <nl> + population = tf . feature_column . numeric_column ( ' population ' ) <nl> + crime_rate = tf . feature_column . numeric_column ( ' crime_rate ' ) <nl> + median_education = tf . feature_column . numeric_column ( ' median_education ' , <nl> + normalizer_fn = ' lambda x : x - global_education_mean ' ) <nl> + <nl> + 3 . * * Instantiate the relevant pre - made Estimator . * * For example , here ' s <nl> + a sample instantiation of a pre - made Estimator named ` LinearClassifier ` : <nl> + <nl> + # Instantiate an estimator , passing the feature columns . <nl> + estimator = tf . estimator . Estimator . LinearClassifier ( <nl> + feature_columns = [ population , crime_rate , median_education ] , <nl> + ) <nl> + <nl> + 4 . * * Call a training , evaluation , or inference method . * * <nl> + For example , all Estimators provide a ` train ` method , which trains a model . <nl> + <nl> + # my_training_set is the function created in Step 1 <nl> + estimator . train ( input_fn = my_training_set , steps = 2000 ) <nl> + <nl> + <nl> + # # # Benefits of pre - made Estimators <nl> + <nl> + Pre - made Estimators encode best practices , providing the following benefits : <nl> + <nl> + * Best practices for determining where different parts of the computational <nl> + graph should run , implementing strategies on a single machine or on a <nl> + cluster . <nl> + * Best practices for event ( summary ) writing and universally useful <nl> + summaries . <nl> + <nl> + If you don ' t use pre - made Estimators , you must implement the preceding <nl> + features yourself . <nl> + <nl> + <nl> + # # Custom Estimators <nl> + <nl> + The heart of every Estimator - - whether pre - made or custom - - is its <nl> + * * model function * * , which is a method that builds graphs for training , <nl> + evaluation , and prediction . When you are using a pre - made Estimator , <nl> + someone else has already implemented the model function . When relying <nl> + on a custom Estimator , you must write the model function yourself . A <nl> + $ { $ extend / estimators $ companion document ) <nl> + explains how to write the model function . <nl> + <nl> + <nl> + # # Recommended workflow <nl> + <nl> + We recommend the following workflow : <nl> + <nl> + 1 . Assuming a suitable pre - made Estimator exists , use it to build your <nl> + first model and use its results to establish a baseline . <nl> + 2 . Build and test your overall pipeline , including the integrity and <nl> + reliability of your data with this pre - made Estimator . <nl> + 3 . If suitable alternative pre - made Estimators are available , run <nl> + experiments to determine which pre - made Estimator produces the <nl> + best results . <nl> + 4 . Possibly , further improve your model by building your own custom Estimator . <nl> + <nl> mmm a / tensorflow / python / framework / function_test . py <nl> ppp b / tensorflow / python / framework / function_test . py <nl> def MyFn ( x ) : <nl> " assertion " ) : <nl> _ = MyFn ( 100 . 0 ) . eval ( ) <nl> <nl> + def testWhileLoopCallsFunc ( self ) : <nl> + with self . test_session ( use_gpu = True ) as sess : <nl> + <nl> + @ function . Defun ( dtypes . float32 ) <nl> + def Times2 ( x ) : <nl> + constant_two = constant_op . constant ( 2 , dtypes . int32 ) <nl> + two_on_gpu = math_ops . cast ( constant_two , dtypes . float32 ) <nl> + return x * two_on_gpu <nl> + <nl> + def Body ( x ) : <nl> + x2 = Times2 ( x ) <nl> + x2 . set_shape ( [ ] ) <nl> + return x2 <nl> + <nl> + loop = control_flow_ops . while_loop ( lambda x : x < 1e5 , Body , [ 1 . 0 ] ) <nl> + <nl> + ans = sess . run ( loop ) <nl> + self . assertAllClose ( ans , 131072 . ) <nl> + <nl> def testControlFlowStrictness ( self ) : <nl> " " " Inlined functions must not execute in a untaken control flow branch . " " " <nl> <nl> def BN1 ( x ) : <nl> self . assertAllClose ( vals [ 2 ] , vals [ 3 ] ) <nl> <nl> def testDeclare ( self ) : <nl> - foo = function . Declare ( " Foo " , [ ( " x " , dtypes . float32 ) ] , <nl> - [ ( " y " , dtypes . float32 ) ] ) <nl> + foo = function . Declare ( " Foo " , [ ( " x " , dtypes . float32 ) ] , [ ( " y " , <nl> + dtypes . float32 ) ] ) <nl> <nl> @ function . Defun ( dtypes . float32 , func_name = " Foo " , out_names = [ " y " ] ) <nl> def FooImpl ( x ) : <nl> def FooImpl ( x ) : <nl> self . assertAllClose ( expected , y . eval ( feed_dict = { x : rand } ) ) <nl> <nl> def testDeclareUsedInDefun ( self ) : <nl> - foo = function . Declare ( " Foo " , [ ( " x " , dtypes . float32 ) ] , <nl> - [ ( " y " , dtypes . float32 ) ] ) <nl> + foo = function . Declare ( " Foo " , [ ( " x " , dtypes . float32 ) ] , [ ( " y " , <nl> + dtypes . float32 ) ] ) <nl> <nl> @ function . Defun ( ) <nl> def Bar ( x ) : <nl> def FooImpl ( x ) : <nl> self . assertAllClose ( expected , y . eval ( feed_dict = { x : rand } ) ) <nl> <nl> def testDeclareTypeMistake ( self ) : <nl> - foo = function . Declare ( " Foo " , [ ( " x " , dtypes . float32 ) ] , <nl> - [ ( " y " , dtypes . float32 ) ] ) <nl> + foo = function . Declare ( " Foo " , [ ( " x " , dtypes . float32 ) ] , [ ( " y " , <nl> + dtypes . float32 ) ] ) <nl> <nl> @ function . Defun ( dtypes . float32 , func_name = " Foo " , out_names = [ " y " ] ) <nl> def Foo ( x ) : <nl> def Inner ( x , unused_y , unused_z ) : <nl> self . assertAllEqual ( v1 , 20 . ) <nl> <nl> def testShapeFunction ( self ) : <nl> - @ function . Defun ( dtypes . float32 , <nl> - shape_func = lambda op : [ op . inputs [ 0 ] . get_shape ( ) ] ) <nl> + <nl> + @ function . Defun ( <nl> + dtypes . float32 , shape_func = lambda op : [ op . inputs [ 0 ] . get_shape ( ) ] ) <nl> def Foo ( x ) : <nl> return x + 1 . 0 <nl> <nl> def Bar ( x ) : <nl> self . assertAllEqual ( y . get_shape ( ) . as_list ( ) , [ 1 , 1 , 2 , 3 ] ) <nl> <nl> def testVariableReuse ( self ) : <nl> + <nl> def LinearWithReuse ( input_tensor , reuse = None ) : <nl> size = input_tensor . shape . dims [ 1 ] <nl> with variable_scope . variable_scope ( " linear " , reuse = reuse ) : <nl> - w = variable_scope . get_variable ( " w " , shape = [ size , size ] , <nl> - dtype = input_tensor . dtype ) <nl> + w = variable_scope . get_variable ( <nl> + " w " , shape = [ size , size ] , dtype = input_tensor . dtype ) <nl> return math_ops . matmul ( input_tensor , w ) <nl> <nl> @ function . Defun ( dtypes . float32 ) <nl> def Foo ( inputs ) : <nl> <nl> with session . Session ( ) as sess : <nl> sess . run ( variables . global_variables_initializer ( ) ) <nl> - output_val = sess . run ( output_op , <nl> - feed_dict = { input_op : np . random . rand ( 32 , 100 ) } ) <nl> + output_val = sess . run ( <nl> + output_op , feed_dict = { input_op : np . random . rand ( 32 , 100 ) } ) <nl> self . assertEqual ( output_val . shape , ( 32 , 100 ) ) <nl> <nl> def testFunctionCallInDifferentVariableScopes ( self ) : <nl> + <nl> @ function . Defun ( dtypes . float32 ) <nl> def Foo ( inputs ) : <nl> - var = variable_scope . get_variable ( " var " , shape = [ 10 ] , dtype = dtypes . float32 , <nl> - initializer = init_ops . ones_initializer ( ) ) <nl> + var = variable_scope . get_variable ( <nl> + " var " , <nl> + shape = [ 10 ] , <nl> + dtype = dtypes . float32 , <nl> + initializer = init_ops . ones_initializer ( ) ) <nl> return inputs + var <nl> <nl> input_op = array_ops . placeholder ( shape = [ 10 ] , dtype = dtypes . float32 ) <nl> def Foo ( inputs ) : <nl> <nl> with session . Session ( ) as sess : <nl> sess . run ( variables . global_variables_initializer ( ) ) <nl> - out1 , out2 = sess . run ( [ out1_op , out2_op ] , <nl> - feed_dict = { input_op : np . linspace ( 1 , 10 , 10 ) } ) <nl> + out1 , out2 = sess . run ( <nl> + [ out1_op , out2_op ] , feed_dict = { input_op : np . linspace ( 1 , 10 , 10 ) } ) <nl> self . assertAllEqual ( out1 , np . linspace ( 2 , 11 , 10 ) ) <nl> self . assertAllEqual ( out2 , np . linspace ( 2 , 11 , 10 ) ) <nl> <nl> def expectFunctionsEqual ( self , func , grad_func = None , new_func = None ) : <nl> self . assertEqual ( func . captured_inputs , new_func . captured_inputs ) <nl> <nl> def testBasic ( self ) : <nl> + <nl> @ function . Defun ( dtypes . float32 , dtypes . float32 ) <nl> def Foo ( x , y ) : <nl> return x + y <nl> + <nl> self . expectFunctionsEqual ( Foo ) <nl> <nl> def testGradFunc ( self ) : <nl> + <nl> @ function . Defun ( dtypes . float32 , dtypes . float32 ) <nl> def G ( x , dy ) : <nl> return x * dy <nl> def G ( x , dy ) : <nl> @ function . Defun ( dtypes . float32 , grad_func = G ) <nl> def F ( x ) : <nl> return math_ops . exp ( x ) - math_ops . exp ( - x ) <nl> + <nl> self . expectFunctionsEqual ( F , grad_func = G ) <nl> <nl> def testCapturedInputs ( self ) : <nl> c = constant_op . constant ( 10 , dtypes . int64 ) <nl> + <nl> @ function . Defun ( dtypes . int64 ) <nl> def Foo ( x ) : <nl> return x + c <nl> def Foo ( x ) : <nl> self . assertEqual ( len ( new_func . captured_inputs ) , 0 ) <nl> <nl> def testNestedFunctions ( self ) : <nl> + <nl> @ function . Defun ( dtypes . float32 ) <nl> def Outer ( x ) : <nl> <nl> def testFromLibraryEmptyLib ( self ) : <nl> self . assertEqual ( len ( function . _from_library ( library ) ) , 0 ) <nl> <nl> def testFromLibraryMissingFuncDef ( self ) : <nl> + <nl> @ function . Defun ( dtypes . float32 , dtypes . float32 ) <nl> def G1 ( x , dy ) : <nl> return x * dy <nl> def F1 ( x ) : <nl> function . _from_library ( library ) <nl> <nl> def testFromLibraryCyclicGradFuncs ( self ) : <nl> + <nl> @ function . Defun ( dtypes . float32 ) <nl> def F1 ( x ) : <nl> return math_ops . exp ( x ) - math_ops . exp ( - x ) <nl> def Forward ( x ) : <nl> inp = np . random . uniform ( - 1 , 1 , [ 16 , 1 ] ) . astype ( np . float32 ) <nl> run_metadata = config_pb2 . RunMetadata ( ) <nl> with session . Session ( graph = g , config = cfg ) as sess : <nl> - ans = sess . run ( [ y , dx ] , { x : inp } , <nl> - run_metadata = run_metadata , <nl> - options = config_pb2 . RunOptions ( <nl> - trace_level = config_pb2 . RunOptions . FULL_TRACE ) ) <nl> + ans = sess . run ( <nl> + [ y , dx ] , { x : inp } , <nl> + run_metadata = run_metadata , <nl> + options = config_pb2 . RunOptions ( <nl> + trace_level = config_pb2 . RunOptions . FULL_TRACE ) ) <nl> print ( ans [ 0 ] , np . sum ( ans [ 1 ] ) ) <nl> self . assertAllClose ( ans [ 0 ] , 255 . 971 , rtol = 1e - 3 ) <nl> self . assertAllClose ( np . sum ( ans [ 1 ] ) , 13 . 0408 , rtol = 1e - 3 ) <nl> class ModuleFunctionTest ( test . TestCase ) : <nl> def testBasic ( self ) : <nl> with ops . Graph ( ) . as_default ( ) : <nl> a , b , c , d , e = [ <nl> - constant_op . constant ( <nl> - [ [ _ ] ] , dtype = dtypes . float32 ) for _ in range ( 5 ) <nl> + constant_op . constant ( [ [ _ ] ] , dtype = dtypes . float32 ) for _ in range ( 5 ) <nl> ] <nl> y = Linear ( a , b , c ) <nl> z = Linear2 ( a , b , c , d , e ) <nl> def _Model ( x ) : <nl> initializer = init_ops . random_uniform_initializer ( seed = 312 ) , <nl> use_resource = use_resource ) <nl> b = variable_scope . get_variable ( <nl> - " b " , ( 64 ) , initializer = init_ops . zeros_initializer ( ) , <nl> + " b " , ( 64 ) , <nl> + initializer = init_ops . zeros_initializer ( ) , <nl> use_resource = use_resource ) , <nl> return math_ops . sigmoid ( math_ops . matmul ( x , w ) + b ) <nl> <nl> def testBasicResource ( self ) : <nl> self . _testSimpleModel ( True , use_resource = True ) <nl> self . _testSimpleModel ( False , use_resource = True ) <nl> <nl> + <nl> if __name__ = = " __main__ " : <nl> test . main ( ) <nl> mmm a / tensorflow / python / training / input . py <nl> ppp b / tensorflow / python / training / input . py <nl> def input_producer ( input_tensor , <nl> " " " <nl> with ops . name_scope ( name , " input_producer " , [ input_tensor ] ) : <nl> input_tensor = ops . convert_to_tensor ( input_tensor , name = " input_tensor " ) <nl> - element_shape = input_tensor . get_shape ( ) [ 1 : ] . merge_with ( element_shape ) <nl> + element_shape = input_tensor . shape [ 1 : ] . merge_with ( element_shape ) <nl> if not element_shape . is_fully_defined ( ) : <nl> raise ValueError ( " Either ` input_tensor ` must have a fully defined shape " <nl> " or ` element_shape ` must be specified " ) <nl> def input_producer ( input_tensor , <nl> q , [ enq ] , cancel_op = cancel_op ) ) <nl> if summary_name is not None : <nl> summary . scalar ( summary_name , <nl> - math_ops . cast ( q . size ( ) , dtypes . float32 ) * ( 1 . / capacity ) ) <nl> + math_ops . to_float ( q . size ( ) ) * ( 1 . / capacity ) ) <nl> return q <nl> <nl> <nl> def _store_sparse_tensors ( tensor_list , enqueue_many , keep_input , <nl> def _sparse_meta_data ( t , storing_op , map_op ) : <nl> if not isinstance ( t , sparse_tensor . SparseTensor ) : <nl> return _SparseMetaData ( False , None , None ) <nl> - rank = t . dense_shape . get_shape ( ) . with_rank ( 1 ) [ 0 ] <nl> + rank = t . dense_shape . shape . with_rank ( 1 ) [ 0 ] <nl> if enqueue_many : <nl> rank - = 1 <nl> # If a shared map_op was provided , use that . Otherwise use the name of <nl> def _maybe_store_many_sparse ( t , map_op_name , keep_input ) : <nl> lambda : - 1 * array_ops . ones ( array_ops . shape ( t ) [ 0 : 1 ] , dtypes . int64 ) ) <nl> out_tensor . set_shape ( [ None ] ) # necessary when t . ndims is unknown <nl> return out_tensor <nl> - if keep_input . get_shape ( ) . ndims = = 1 : <nl> + if keep_input . shape . ndims = = 1 : <nl> t = sparse_ops . sparse_retain ( t , keep_input ) <nl> store_f = lambda t , name , _ : _store_many_sparse ( t , shared_name = name ) <nl> elif enqueue_many : <nl> def _validate_join ( tensor_list_list ) : <nl> def _validate_keep_input ( keep_input , enqueue_many ) : <nl> " " " Validate ` keep_input ` argument to conditional batching functions . " " " <nl> keep_input = ops . convert_to_tensor ( keep_input ) <nl> - if keep_input . get_shape ( ) . ndims is None : <nl> + if keep_input . shape . ndims is None : <nl> raise ValueError ( <nl> " ` keep_input ` dimensions must be known at graph construction . " ) <nl> - if not enqueue_many and keep_input . get_shape ( ) . ndims = = 1 : <nl> + if not enqueue_many and keep_input . shape . ndims = = 1 : <nl> raise ValueError ( <nl> " ` keep_input ` cannot be a vector when ` enqueue_many = False ` . " ) <nl> - if keep_input . get_shape ( ) . ndims > 1 : <nl> + if keep_input . shape . ndims > 1 : <nl> raise ValueError ( " ` keep_input ` must be 0 or 1 dimensions . " ) <nl> return keep_input <nl> <nl> def _shapes ( tensor_list_list , shapes , enqueue_many ) : <nl> <nl> for tl in tensor_list_list : <nl> for i in xrange ( len0 ) : <nl> - if tl [ i ] . get_shape ( ) . ndims is None : <nl> + if tl [ i ] . shape . ndims is None : <nl> raise ValueError ( " Cannot infer Tensor ' s rank : % s " % tl [ i ] ) <nl> <nl> shapes = [ _merge_shapes ( <nl> - [ tl [ i ] . get_shape ( ) . as_list ( ) for tl in tensor_list_list ] , enqueue_many ) <nl> + [ tl [ i ] . shape . as_list ( ) for tl in tensor_list_list ] , enqueue_many ) <nl> for i in xrange ( len0 ) ] <nl> return shapes <nl> <nl> <nl> def _select_which_to_enqueue ( tensor_list , keep_input ) : <nl> " " " Select which examples to enqueue based on vector ` keep_input ` . " " " <nl> - select_i = math_ops . cast ( keep_input , dtypes . int32 ) <nl> + select_i = math_ops . to_int32 ( keep_input ) <nl> tensor_list = [ <nl> data_flow_ops . dynamic_partition ( x , select_i , num_partitions = 2 ) [ 1 ] <nl> for x in tensor_list ] <nl> def _enqueue_join ( queue , tensor_list_list , enqueue_many , keep_input ) : <nl> enqueue_fn = queue . enqueue_many <nl> else : <nl> enqueue_fn = queue . enqueue <nl> - if keep_input . get_shape ( ) . ndims = = 1 : <nl> + if keep_input . shape . ndims = = 1 : <nl> enqueue_ops = [ enqueue_fn ( _select_which_to_enqueue ( x , keep_input ) ) <nl> for x in tensor_list_list ] <nl> else : <nl> def _enqueue ( queue , tensor_list , threads , enqueue_many , keep_input ) : <nl> enqueue_fn = queue . enqueue_many <nl> else : <nl> enqueue_fn = queue . enqueue <nl> - if keep_input . get_shape ( ) . ndims = = 1 : <nl> + if keep_input . shape . ndims = = 1 : <nl> enqueue_ops = [ <nl> enqueue_fn ( _select_which_to_enqueue ( tensor_list , keep_input ) ) ] * threads <nl> else : <nl> def _batch ( tensors , batch_size , keep_input , num_threads = 1 , capacity = 32 , <nl> capacity = capacity , dtypes = types , shapes = shapes , shared_name = shared_name ) <nl> _enqueue ( queue , tensor_list , num_threads , enqueue_many , keep_input ) <nl> summary . scalar ( " fraction_of_ % d_full " % capacity , <nl> - math_ops . cast ( queue . size ( ) , dtypes . float32 ) * <nl> - ( 1 . / capacity ) ) <nl> + math_ops . to_float ( queue . size ( ) ) * ( 1 . / capacity ) ) <nl> <nl> if allow_smaller_final_batch : <nl> dequeued = queue . dequeue_up_to ( batch_size , name = name ) <nl> def _batch_join ( tensors_list , batch_size , keep_input , capacity = 32 , <nl> capacity = capacity , dtypes = types , shapes = shapes , shared_name = shared_name ) <nl> _enqueue_join ( queue , tensor_list_list , enqueue_many , keep_input ) <nl> summary . scalar ( " fraction_of_ % d_full " % capacity , <nl> - math_ops . cast ( queue . size ( ) , dtypes . float32 ) * <nl> - ( 1 . / capacity ) ) <nl> + math_ops . to_float ( queue . size ( ) ) * ( 1 . / capacity ) ) <nl> <nl> if allow_smaller_final_batch : <nl> dequeued = queue . dequeue_up_to ( batch_size , name = name ) <nl> def _shuffle_batch ( tensors , batch_size , capacity , min_after_dequeue , <nl> capacity = capacity , min_after_dequeue = min_after_dequeue , seed = seed , <nl> dtypes = types , shapes = shapes , shared_name = shared_name ) <nl> _enqueue ( queue , tensor_list , num_threads , enqueue_many , keep_input ) <nl> - full = ( math_ops . cast ( math_ops . maximum ( 0 , queue . size ( ) - min_after_dequeue ) , <nl> - dtypes . float32 ) * <nl> + full = ( math_ops . to_float ( <nl> + math_ops . maximum ( 0 , queue . size ( ) - min_after_dequeue ) ) * <nl> ( 1 . / ( capacity - min_after_dequeue ) ) ) <nl> # Note that name contains a ' / ' at the end so we intentionally do not place <nl> # a ' / ' after % s below . <nl> def _shuffle_batch_join ( tensors_list , batch_size , capacity , <nl> capacity = capacity , min_after_dequeue = min_after_dequeue , seed = seed , <nl> dtypes = types , shapes = shapes , shared_name = shared_name ) <nl> _enqueue_join ( queue , tensor_list_list , enqueue_many , keep_input ) <nl> - full = ( math_ops . cast ( math_ops . maximum ( 0 , queue . size ( ) - min_after_dequeue ) , <nl> - dtypes . float32 ) * <nl> + full = ( math_ops . to_float ( <nl> + math_ops . maximum ( 0 , queue . size ( ) - min_after_dequeue ) ) * <nl> ( 1 . / ( capacity - min_after_dequeue ) ) ) <nl> # Note that name contains a ' / ' at the end so we intentionally do not place <nl> # a ' / ' after % s below . <nl>
Merge pull request from vrv / branch_163213141
tensorflow/tensorflow
ae22de6596974f6231ea0cd47b67149b9a708e9e
2017-07-26T20:09:00Z
mmm a / src / Core / Settings . h <nl> ppp b / src / Core / Settings . h <nl> struct Settings : public SettingsCollection < Settings > <nl> * A setting is " IMPORTANT " if it affects the results of queries and can ' t be ignored by older versions . <nl> * / <nl> <nl> - # define LIST_OF_SETTINGS ( M ) \ <nl> + # define COMMON_SETTINGS ( M ) \ <nl> M ( SettingUInt64 , min_compress_block_size , 65536 , " The actual size of the block to compress , if the uncompressed data less than max_compress_block_size is no less than this value and no less than the volume of data for one mark . " , 0 ) \ <nl> M ( SettingUInt64 , max_compress_block_size , 1048576 , " The maximum size of blocks of uncompressed data before compressing for writing to a table . " , 0 ) \ <nl> M ( SettingUInt64 , max_block_size , DEFAULT_BLOCK_SIZE , " Maximum block size for reading " , 0 ) \ <nl> struct Settings : public SettingsCollection < Settings > <nl> \ <nl> M ( SettingString , count_distinct_implementation , " uniqExact " , " What aggregate function to use for implementation of count ( DISTINCT . . . ) " , 0 ) \ <nl> \ <nl> - M ( SettingBool , output_format_enable_streaming , false , " Enable streaming in output formats that support it . " , 0 ) \ <nl> - M ( SettingBool , output_format_write_statistics , true , " Write statistics about read rows , bytes , time elapsed in suitable output formats . " , 0 ) \ <nl> - \ <nl> M ( SettingBool , add_http_cors_header , false , " Write add http CORS header . " , 0 ) \ <nl> \ <nl> M ( SettingUInt64 , max_http_get_redirects , 0 , " Max number of http GET redirects hops allowed . Make sure additional security measures are in place to prevent a malicious server to redirect your requests to unexpected services . " , 0 ) \ <nl> \ <nl> - M ( SettingBool , input_format_skip_unknown_fields , false , " Skip columns with unknown names from input data ( it works for JSONEachRow , CSVWithNames , TSVWithNames and TSKV formats ) . " , 0 ) \ <nl> - M ( SettingBool , input_format_with_names_use_header , true , " For TSVWithNames and CSVWithNames input formats this controls whether format parser is to assume that column data appear in the input exactly as they are specified in the header . " , 0 ) \ <nl> - M ( SettingBool , input_format_import_nested_json , false , " Map nested JSON data to nested tables ( it works for JSONEachRow format ) . " , 0 ) \ <nl> - M ( SettingBool , input_format_defaults_for_omitted_fields , true , " For input data calculate default expressions for omitted fields ( it works for JSONEachRow , CSV and TSV formats ) . " , IMPORTANT ) \ <nl> - M ( SettingBool , input_format_tsv_empty_as_default , false , " Treat empty fields in TSV input as default values . " , 0 ) \ <nl> - M ( SettingBool , input_format_null_as_default , false , " For text input formats initialize null fields with default values if data type of this field is not nullable " , 0 ) \ <nl> - \ <nl> - M ( SettingBool , input_format_values_interpret_expressions , true , " For Values format : if the field could not be parsed by streaming parser , run SQL parser and try to interpret it as SQL expression . " , 0 ) \ <nl> - M ( SettingBool , input_format_values_deduce_templates_of_expressions , true , " For Values format : if the field could not be parsed by streaming parser , run SQL parser , deduce template of the SQL expression , try to parse all rows using template and then interpret expression for all rows . " , 0 ) \ <nl> - M ( SettingBool , input_format_values_accurate_types_of_literals , true , " For Values format : when parsing and interpreting expressions using template , check actual type of literal to avoid possible overflow and precision issues . " , 0 ) \ <nl> - M ( SettingURI , format_avro_schema_registry_url , { } , " For AvroConfluent format : Confluent Schema Registry URL . " , 0 ) \ <nl> - \ <nl> - M ( SettingBool , output_format_json_quote_64bit_integers , true , " Controls quoting of 64 - bit integers in JSON output format . " , 0 ) \ <nl> - \ <nl> - M ( SettingBool , output_format_json_quote_denormals , false , " Enables ' + nan ' , ' - nan ' , ' + inf ' , ' - inf ' outputs in JSON output format . " , 0 ) \ <nl> - \ <nl> - M ( SettingBool , output_format_json_escape_forward_slashes , true , " Controls escaping forward slashes for string outputs in JSON output format . This is intended for compatibility with JavaScript . Don ' t confuse with backslashes that are always escaped . " , 0 ) \ <nl> - \ <nl> - M ( SettingUInt64 , output_format_pretty_max_rows , 10000 , " Rows limit for Pretty formats . " , 0 ) \ <nl> - M ( SettingUInt64 , output_format_pretty_max_column_pad_width , 250 , " Maximum width to pad all values in a column in Pretty formats . " , 0 ) \ <nl> - M ( SettingUInt64 , output_format_pretty_max_value_width , 10000 , " Maximum width of value to display in Pretty formats . If greater - it will be cut . " , 0 ) \ <nl> - M ( SettingBool , output_format_pretty_color , true , " Use ANSI escape sequences to paint colors in Pretty formats " , 0 ) \ <nl> - M ( SettingUInt64 , output_format_parquet_row_group_size , 1000000 , " Row group size in rows . " , 0 ) \ <nl> - M ( SettingString , output_format_avro_codec , " " , " Compression codec used for output . Possible values : ' null ' , ' deflate ' , ' snappy ' . " , 0 ) \ <nl> - M ( SettingUInt64 , output_format_avro_sync_interval , 16 * 1024 , " Sync interval in bytes . " , 0 ) \ <nl> - M ( SettingBool , output_format_tsv_crlf_end_of_line , false , " If it is set true , end of line in TSV format will be \ \ r \ \ n instead of \ \ n . " , 0 ) \ <nl> - \ <nl> M ( SettingBool , use_client_time_zone , false , " Use client timezone for interpreting DateTime string values , instead of adopting server timezone . " , 0 ) \ <nl> \ <nl> M ( SettingBool , send_progress_in_http_headers , false , " Send progress notifications using X - ClickHouse - Progress headers . Some clients do not support high amount of HTTP headers ( Python requests in particular ) , so it is disabled by default . " , 0 ) \ <nl> struct Settings : public SettingsCollection < Settings > <nl> \ <nl> M ( SettingBool , fsync_metadata , 1 , " Do fsync after changing metadata for tables and databases ( . sql files ) . Could be disabled in case of poor latency on server with high load of DDL queries and high load of disk subsystem . " , 0 ) \ <nl> \ <nl> - M ( SettingUInt64 , input_format_allow_errors_num , 0 , " Maximum absolute amount of errors while reading text formats ( like CSV , TSV ) . In case of error , if at least absolute or relative amount of errors is lower than corresponding value , will skip until next line and continue . " , 0 ) \ <nl> - M ( SettingFloat , input_format_allow_errors_ratio , 0 , " Maximum relative amount of errors while reading text formats ( like CSV , TSV ) . In case of error , if at least absolute or relative amount of errors is lower than corresponding value , will skip until next line and continue . " , 0 ) \ <nl> - \ <nl> M ( SettingBool , join_use_nulls , 0 , " Use NULLs for non - joined rows of outer JOINs for types that can be inside Nullable . If false , use default value of corresponding columns data type . " , IMPORTANT ) \ <nl> \ <nl> M ( SettingJoinStrictness , join_default_strictness , JoinStrictness : : ALL , " Set default strictness in JOIN query . Possible values : empty string , ' ANY ' , ' ALL ' . If empty , query without strictness will throw exception . " , 0 ) \ <nl> struct Settings : public SettingsCollection < Settings > <nl> M ( SettingMilliseconds , stream_flush_interval_ms , 7500 , " Timeout for flushing data from streaming storages . " , 0 ) \ <nl> M ( SettingMilliseconds , stream_poll_timeout_ms , 500 , " Timeout for polling data from / to streaming storages . " , 0 ) \ <nl> \ <nl> - M ( SettingString , format_schema , " " , " Schema identifier ( used by schema - based formats ) " , 0 ) \ <nl> - M ( SettingString , format_template_resultset , " " , " Path to file which contains format string for result set ( for Template format ) " , 0 ) \ <nl> - M ( SettingString , format_template_row , " " , " Path to file which contains format string for rows ( for Template format ) " , 0 ) \ <nl> - M ( SettingString , format_template_rows_between_delimiter , " \ n " , " Delimiter between rows ( for Template format ) " , 0 ) \ <nl> - \ <nl> - M ( SettingString , format_custom_escaping_rule , " Escaped " , " Field escaping rule ( for CustomSeparated format ) " , 0 ) \ <nl> - M ( SettingString , format_custom_field_delimiter , " \ t " , " Delimiter between fields ( for CustomSeparated format ) " , 0 ) \ <nl> - M ( SettingString , format_custom_row_before_delimiter , " " , " Delimiter before field of the first column ( for CustomSeparated format ) " , 0 ) \ <nl> - M ( SettingString , format_custom_row_after_delimiter , " \ n " , " Delimiter after field of the last column ( for CustomSeparated format ) " , 0 ) \ <nl> - M ( SettingString , format_custom_row_between_delimiter , " " , " Delimiter between rows ( for CustomSeparated format ) " , 0 ) \ <nl> - M ( SettingString , format_custom_result_before_delimiter , " " , " Prefix before result set ( for CustomSeparated format ) " , 0 ) \ <nl> - M ( SettingString , format_custom_result_after_delimiter , " " , " Suffix after result set ( for CustomSeparated format ) " , 0 ) \ <nl> - \ <nl> - M ( SettingString , format_regexp , " " , " Regular expression ( for Regexp format ) " , 0 ) \ <nl> - M ( SettingString , format_regexp_escaping_rule , " Escaped " , " Field escaping rule ( for Regexp format ) " , 0 ) \ <nl> - M ( SettingBool , format_regexp_skip_unmatched , false , " Skip lines unmatched by regular expression ( for Regexp format " , 0 ) \ <nl> - \ <nl> M ( SettingBool , insert_allow_materialized_columns , 0 , " If setting is enabled , Allow materialized columns in INSERT . " , 0 ) \ <nl> M ( SettingSeconds , http_connection_timeout , DEFAULT_HTTP_READ_BUFFER_CONNECTION_TIMEOUT , " HTTP connection timeout . " , 0 ) \ <nl> M ( SettingSeconds , http_send_timeout , DEFAULT_HTTP_READ_BUFFER_TIMEOUT , " HTTP send timeout " , 0 ) \ <nl> struct Settings : public SettingsCollection < Settings > <nl> M ( SettingUInt64 , max_network_bytes , 0 , " The maximum number of bytes ( compressed ) to receive or transmit over the network for execution of the query . " , 0 ) \ <nl> M ( SettingUInt64 , max_network_bandwidth_for_user , 0 , " The maximum speed of data exchange over the network in bytes per second for all concurrently running user queries . Zero means unlimited . " , 0 ) \ <nl> M ( SettingUInt64 , max_network_bandwidth_for_all_users , 0 , " The maximum speed of data exchange over the network in bytes per second for all concurrently running queries . Zero means unlimited . " , 0 ) \ <nl> - M ( SettingChar , format_csv_delimiter , ' , ' , " The character to be considered as a delimiter in CSV data . If setting with a string , a string has to have a length of 1 . " , 0 ) \ <nl> - M ( SettingBool , format_csv_allow_single_quotes , 1 , " If it is set to true , allow strings in single quotes . " , 0 ) \ <nl> - M ( SettingBool , format_csv_allow_double_quotes , 1 , " If it is set to true , allow strings in double quotes . " , 0 ) \ <nl> - M ( SettingBool , output_format_csv_crlf_end_of_line , false , " If it is set true , end of line in CSV format will be \ \ r \ \ n instead of \ \ n . " , 0 ) \ <nl> - M ( SettingBool , input_format_csv_unquoted_null_literal_as_null , false , " Consider unquoted NULL literal as \ \ N " , 0 ) \ <nl> \ <nl> - M ( SettingDateTimeInputFormat , date_time_input_format , FormatSettings : : DateTimeInputFormat : : Basic , " Method to read DateTime from text input formats . Possible values : ' basic ' and ' best_effort ' . " , 0 ) \ <nl> M ( SettingBool , log_profile_events , true , " Log query performance statistics into the query_log and query_thread_log . " , 0 ) \ <nl> M ( SettingBool , log_query_settings , true , " Log query settings into the query_log . " , 0 ) \ <nl> M ( SettingBool , log_query_threads , true , " Log query threads into system . query_thread_log table . This setting have effect only when ' log_queries ' is true . " , 0 ) \ <nl> struct Settings : public SettingsCollection < Settings > <nl> M ( SettingUInt64 , mark_cache_min_lifetime , 0 , " Obsolete setting , does nothing . Will be removed after 2020 - 05 - 31 " , 0 ) \ <nl> M ( SettingBool , partial_merge_join , false , " Obsolete . Use join_algorithm = ' prefer_partial_merge ' instead . " , 0 ) \ <nl> M ( SettingUInt64 , max_memory_usage_for_all_queries , 0 , " Obsolete . Will be removed after 2020 - 10 - 20 " , 0 ) \ <nl> - M ( SettingBool , experimental_use_processors , true , " Obsolete setting , does nothing . Will be removed after 2020 - 11 - 29 . " , 0 ) \ <nl> + M ( SettingBool , experimental_use_processors , true , " Obsolete setting , does nothing . Will be removed after 2020 - 11 - 29 . " , 0 ) <nl> + <nl> + # define FORMAT_FACTORY_SETTINGS ( M ) \ <nl> + M ( SettingChar , format_csv_delimiter , ' , ' , " The character to be considered as a delimiter in CSV data . If setting with a string , a string has to have a length of 1 . " , 0 ) \ <nl> + M ( SettingBool , format_csv_allow_single_quotes , 1 , " If it is set to true , allow strings in single quotes . " , 0 ) \ <nl> + M ( SettingBool , format_csv_allow_double_quotes , 1 , " If it is set to true , allow strings in double quotes . " , 0 ) \ <nl> + M ( SettingBool , output_format_csv_crlf_end_of_line , false , " If it is set true , end of line in CSV format will be \ \ r \ \ n instead of \ \ n . " , 0 ) \ <nl> + M ( SettingBool , input_format_csv_unquoted_null_literal_as_null , false , " Consider unquoted NULL literal as \ \ N " , 0 ) \ <nl> + M ( SettingBool , input_format_skip_unknown_fields , false , " Skip columns with unknown names from input data ( it works for JSONEachRow , CSVWithNames , TSVWithNames and TSKV formats ) . " , 0 ) \ <nl> + M ( SettingBool , input_format_with_names_use_header , true , " For TSVWithNames and CSVWithNames input formats this controls whether format parser is to assume that column data appear in the input exactly as they are specified in the header . " , 0 ) \ <nl> + M ( SettingBool , input_format_import_nested_json , false , " Map nested JSON data to nested tables ( it works for JSONEachRow format ) . " , 0 ) \ <nl> + M ( SettingBool , input_format_defaults_for_omitted_fields , true , " For input data calculate default expressions for omitted fields ( it works for JSONEachRow , CSV and TSV formats ) . " , IMPORTANT ) \ <nl> + M ( SettingBool , input_format_tsv_empty_as_default , false , " Treat empty fields in TSV input as default values . " , 0 ) \ <nl> + M ( SettingBool , input_format_null_as_default , false , " For text input formats initialize null fields with default values if data type of this field is not nullable " , 0 ) \ <nl> + \ <nl> + M ( SettingDateTimeInputFormat , date_time_input_format , FormatSettings : : DateTimeInputFormat : : Basic , " Method to read DateTime from text input formats . Possible values : ' basic ' and ' best_effort ' . " , 0 ) \ <nl> + \ <nl> + M ( SettingBool , input_format_values_interpret_expressions , true , " For Values format : if the field could not be parsed by streaming parser , run SQL parser and try to interpret it as SQL expression . " , 0 ) \ <nl> + M ( SettingBool , input_format_values_deduce_templates_of_expressions , true , " For Values format : if the field could not be parsed by streaming parser , run SQL parser , deduce template of the SQL expression , try to parse all rows using template and then interpret expression for all rows . " , 0 ) \ <nl> + M ( SettingBool , input_format_values_accurate_types_of_literals , true , " For Values format : when parsing and interpreting expressions using template , check actual type of literal to avoid possible overflow and precision issues . " , 0 ) \ <nl> + M ( SettingURI , format_avro_schema_registry_url , { } , " For AvroConfluent format : Confluent Schema Registry URL . " , 0 ) \ <nl> + \ <nl> + M ( SettingBool , output_format_json_quote_64bit_integers , true , " Controls quoting of 64 - bit integers in JSON output format . " , 0 ) \ <nl> + \ <nl> + M ( SettingBool , output_format_json_quote_denormals , false , " Enables ' + nan ' , ' - nan ' , ' + inf ' , ' - inf ' outputs in JSON output format . " , 0 ) \ <nl> + \ <nl> + M ( SettingBool , output_format_json_escape_forward_slashes , true , " Controls escaping forward slashes for string outputs in JSON output format . This is intended for compatibility with JavaScript . Don ' t confuse with backslashes that are always escaped . " , 0 ) \ <nl> + \ <nl> + M ( SettingUInt64 , output_format_pretty_max_rows , 10000 , " Rows limit for Pretty formats . " , 0 ) \ <nl> + M ( SettingUInt64 , output_format_pretty_max_column_pad_width , 250 , " Maximum width to pad all values in a column in Pretty formats . " , 0 ) \ <nl> + M ( SettingBool , output_format_pretty_color , true , " Use ANSI escape sequences to paint colors in Pretty formats " , 0 ) \ <nl> + M ( SettingUInt64 , output_format_parquet_row_group_size , 1000000 , " Row group size in rows . " , 0 ) \ <nl> + M ( SettingString , output_format_avro_codec , " " , " Compression codec used for output . Possible values : ' null ' , ' deflate ' , ' snappy ' . " , 0 ) \ <nl> + M ( SettingUInt64 , output_format_avro_sync_interval , 16 * 1024 , " Sync interval in bytes . " , 0 ) \ <nl> + M ( SettingBool , output_format_tsv_crlf_end_of_line , false , " If it is set true , end of line in TSV format will be \ \ r \ \ n instead of \ \ n . " , 0 ) \ <nl> + \ <nl> + M ( SettingUInt64 , input_format_allow_errors_num , 0 , " Maximum absolute amount of errors while reading text formats ( like CSV , TSV ) . In case of error , if at least absolute or relative amount of errors is lower than corresponding value , will skip until next line and continue . " , 0 ) \ <nl> + M ( SettingFloat , input_format_allow_errors_ratio , 0 , " Maximum relative amount of errors while reading text formats ( like CSV , TSV ) . In case of error , if at least absolute or relative amount of errors is lower than corresponding value , will skip until next line and continue . " , 0 ) \ <nl> + \ <nl> + M ( SettingString , format_schema , " " , " Schema identifier ( used by schema - based formats ) " , 0 ) \ <nl> + M ( SettingString , format_template_resultset , " " , " Path to file which contains format string for result set ( for Template format ) " , 0 ) \ <nl> + M ( SettingString , format_template_row , " " , " Path to file which contains format string for rows ( for Template format ) " , 0 ) \ <nl> + M ( SettingString , format_template_rows_between_delimiter , " \ n " , " Delimiter between rows ( for Template format ) " , 0 ) \ <nl> + \ <nl> + M ( SettingString , format_custom_escaping_rule , " Escaped " , " Field escaping rule ( for CustomSeparated format ) " , 0 ) \ <nl> + M ( SettingString , format_custom_field_delimiter , " \ t " , " Delimiter between fields ( for CustomSeparated format ) " , 0 ) \ <nl> + M ( SettingString , format_custom_row_before_delimiter , " " , " Delimiter before field of the first column ( for CustomSeparated format ) " , 0 ) \ <nl> + M ( SettingString , format_custom_row_after_delimiter , " \ n " , " Delimiter after field of the last column ( for CustomSeparated format ) " , 0 ) \ <nl> + M ( SettingString , format_custom_row_between_delimiter , " " , " Delimiter between rows ( for CustomSeparated format ) " , 0 ) \ <nl> + M ( SettingString , format_custom_result_before_delimiter , " " , " Prefix before result set ( for CustomSeparated format ) " , 0 ) \ <nl> + M ( SettingString , format_custom_result_after_delimiter , " " , " Suffix after result set ( for CustomSeparated format ) " , 0 ) \ <nl> + \ <nl> + M ( SettingString , format_regexp , " " , " Regular expression ( for Regexp format ) " , 0 ) \ <nl> + M ( SettingString , format_regexp_escaping_rule , " Escaped " , " Field escaping rule ( for Regexp format ) " , 0 ) \ <nl> + M ( SettingBool , format_regexp_skip_unmatched , false , " Skip lines unmatched by regular expression ( for Regexp format " , 0 ) \ <nl> + \ <nl> + M ( SettingBool , output_format_enable_streaming , false , " Enable streaming in output formats that support it . " , 0 ) \ <nl> + M ( SettingBool , output_format_write_statistics , true , " Write statistics about read rows , bytes , time elapsed in suitable output formats . " , 0 ) <nl> + <nl> + # define LIST_OF_SETTINGS ( M ) \ <nl> + COMMON_SETTINGS ( M ) \ <nl> + FORMAT_FACTORY_SETTINGS ( M ) <nl> <nl> DECLARE_SETTINGS_COLLECTION ( LIST_OF_SETTINGS ) <nl> <nl> mmm a / src / Storages / Kafka / KafkaBlockInputStream . cpp <nl> ppp b / src / Storages / Kafka / KafkaBlockInputStream . cpp <nl> KafkaBlockInputStream : : KafkaBlockInputStream ( <nl> , non_virtual_header ( storage . getSampleBlockNonMaterialized ( ) ) <nl> , virtual_header ( storage . getSampleBlockForColumns ( { " _topic " , " _key " , " _offset " , " _partition " , " _timestamp " , " _timestamp_ms " , " _headers . name " , " _headers . value " } ) ) <nl> { <nl> - context . setSetting ( " input_format_skip_unknown_fields " , 1u ) ; / / Always skip unknown fields regardless of the context ( JSON or TSKV ) <nl> - context . setSetting ( " input_format_allow_errors_ratio " , 0 . ) ; <nl> - context . setSetting ( " input_format_allow_errors_num " , storage . skipBroken ( ) ) ; <nl> - <nl> - if ( ! storage . getSchemaName ( ) . empty ( ) ) <nl> - context . setSetting ( " format_schema " , storage . getSchemaName ( ) ) ; <nl> + storage . adjustContext ( context ) ; <nl> } <nl> <nl> KafkaBlockInputStream : : ~ KafkaBlockInputStream ( ) <nl> mmm a / src / Storages / Kafka / KafkaSettings . cpp <nl> ppp b / src / Storages / Kafka / KafkaSettings . cpp <nl> void KafkaSettings : : loadFromQuery ( ASTStorage & storage_def ) <nl> } <nl> } <nl> <nl> + <nl> } <nl> mmm a / src / Storages / Kafka / KafkaSettings . h <nl> ppp b / src / Storages / Kafka / KafkaSettings . h <nl> <nl> # pragma once <nl> <nl> # include < Core / SettingsCollection . h > <nl> - <nl> + # include < Core / Settings . h > <nl> <nl> namespace DB <nl> { <nl> struct KafkaSettings : public SettingsCollection < KafkaSettings > <nl> { <nl> <nl> <nl> - # define LIST_OF_KAFKA_SETTINGS ( M ) \ <nl> + # define KAFKA_RELATED_SETTINGS ( M ) \ <nl> M ( SettingString , kafka_broker_list , " " , " A comma - separated list of brokers for Kafka engine . " , 0 ) \ <nl> M ( SettingString , kafka_topic_list , " " , " A list of Kafka topics . " , 0 ) \ <nl> M ( SettingString , kafka_group_name , " " , " A group of Kafka consumers . " , 0 ) \ <nl> M ( SettingString , kafka_client_id , " " , " A client id of Kafka consumer . " , 0 ) \ <nl> + M ( SettingUInt64 , kafka_num_consumers , 1 , " The number of consumers per table for Kafka engine . " , 0 ) \ <nl> + M ( SettingBool , kafka_commit_every_batch , false , " Commit every consumed and handled batch instead of a single commit after writing a whole block " , 0 ) \ <nl> + / * default is stream_poll_timeout_ms * / \ <nl> + M ( SettingMilliseconds , kafka_poll_timeout_ms , 0 , " Timeout for single poll from Kafka . " , 0 ) \ <nl> + / * default is min ( max_block_size , kafka_max_block_size ) * / \ <nl> + M ( SettingUInt64 , kafka_poll_max_batch_size , 0 , " Maximum amount of messages to be polled in a single Kafka poll . " , 0 ) \ <nl> + / * default is = min_insert_block_size / kafka_num_consumers * / \ <nl> + M ( SettingUInt64 , kafka_max_block_size , 0 , " Number of row collected by poll ( s ) for flushing data from Kafka . " , 0 ) \ <nl> + / * default is stream_flush_interval_ms * / \ <nl> + M ( SettingMilliseconds , kafka_flush_interval_ms , 0 , " Timeout for flushing data from Kafka . " , 0 ) \ <nl> + / * those are mapped to format factory settings * / \ <nl> M ( SettingString , kafka_format , " " , " The message format for Kafka engine . " , 0 ) \ <nl> M ( SettingChar , kafka_row_delimiter , ' \ 0 ' , " The character to be considered as a delimiter in Kafka message . " , 0 ) \ <nl> M ( SettingString , kafka_schema , " " , " Schema identifier ( used by schema - based formats ) for Kafka engine " , 0 ) \ <nl> - M ( SettingUInt64 , kafka_num_consumers , 1 , " The number of consumers per table for Kafka engine . " , 0 ) \ <nl> - M ( SettingUInt64 , kafka_max_block_size , 0 , " The maximum batch size for poll . " , 0 ) \ <nl> - M ( SettingUInt64 , kafka_skip_broken_messages , 0 , " Skip at least this number of broken messages from Kafka topic per block " , 0 ) \ <nl> - M ( SettingUInt64 , kafka_commit_every_batch , 0 , " Commit every consumed and handled batch instead of a single commit after writing a whole block " , 0 ) <nl> + M ( SettingUInt64 , kafka_skip_broken_messages , 0 , " Skip at least this number of broken messages from Kafka topic per block " , 0 ) <nl> + <nl> + # define LIST_OF_KAFKA_SETTINGS ( M ) \ <nl> + KAFKA_RELATED_SETTINGS ( M ) \ <nl> + FORMAT_FACTORY_SETTINGS ( M ) <nl> <nl> DECLARE_SETTINGS_COLLECTION ( LIST_OF_KAFKA_SETTINGS ) <nl> <nl> mmm a / src / Storages / Kafka / StorageKafka . cpp <nl> ppp b / src / Storages / Kafka / StorageKafka . cpp <nl> StorageKafka : : StorageKafka ( <nl> const StorageID & table_id_ , <nl> Context & context_ , <nl> const ColumnsDescription & columns_ , <nl> - const String & brokers_ , <nl> - const String & group_ , <nl> - const String & client_id_ , <nl> - const Names & topics_ , <nl> - const String & format_name_ , <nl> - char row_delimiter_ , <nl> - const String & schema_name_ , <nl> - size_t num_consumers_ , <nl> - UInt64 max_block_size_ , <nl> - size_t skip_broken_ , <nl> - bool intermediate_commit_ ) <nl> + std : : unique_ptr < KafkaSettings > kafka_settings_ ) <nl> : IStorage ( table_id_ ) <nl> , global_context ( context_ . getGlobalContext ( ) ) <nl> , kafka_context ( Context ( global_context ) ) <nl> - , topics ( global_context . getMacros ( ) - > expand ( topics_ ) ) <nl> - , brokers ( global_context . getMacros ( ) - > expand ( brokers_ ) ) <nl> - , group ( global_context . getMacros ( ) - > expand ( group_ ) ) <nl> - , client_id ( client_id_ . empty ( ) ? getDefaultClientId ( table_id_ ) : global_context . getMacros ( ) - > expand ( client_id_ ) ) <nl> - , format_name ( global_context . getMacros ( ) - > expand ( format_name_ ) ) <nl> - , row_delimiter ( row_delimiter_ ) <nl> - , schema_name ( global_context . getMacros ( ) - > expand ( schema_name_ ) ) <nl> - , num_consumers ( num_consumers_ ) <nl> - , max_block_size ( max_block_size_ ) <nl> + , kafka_settings ( std : : move ( kafka_settings_ ) ) <nl> + , topics ( parseTopics ( global_context . getMacros ( ) - > expand ( kafka_settings - > kafka_topic_list . value ) ) ) <nl> + , brokers ( global_context . getMacros ( ) - > expand ( kafka_settings - > kafka_broker_list . value ) ) <nl> + , group ( global_context . getMacros ( ) - > expand ( kafka_settings - > kafka_group_name . value ) ) <nl> + , client_id ( kafka_settings - > kafka_client_id . value . empty ( ) ? getDefaultClientId ( table_id_ ) : global_context . getMacros ( ) - > expand ( kafka_settings - > kafka_client_id . value ) ) <nl> + , format_name ( global_context . getMacros ( ) - > expand ( kafka_settings - > kafka_format . value ) ) <nl> + , row_delimiter ( kafka_settings - > kafka_row_delimiter . value ) <nl> + , schema_name ( global_context . getMacros ( ) - > expand ( kafka_settings - > kafka_schema . value ) ) <nl> + , num_consumers ( kafka_settings - > kafka_num_consumers . value ) <nl> , log ( & Poco : : Logger : : get ( " StorageKafka ( " + table_id_ . table_name + " ) " ) ) <nl> - , semaphore ( 0 , num_consumers_ ) <nl> - , skip_broken ( skip_broken_ ) <nl> - , intermediate_commit ( intermediate_commit_ ) <nl> + , semaphore ( 0 , num_consumers ) <nl> + , intermediate_commit ( kafka_settings - > kafka_commit_every_batch . value ) <nl> { <nl> kafka_context . makeQueryContext ( ) ; <nl> <nl> setColumns ( columns_ ) ; <nl> task = global_context . getSchedulePool ( ) . createTask ( log - > name ( ) , [ this ] { threadFunc ( ) ; } ) ; <nl> task - > deactivate ( ) ; <nl> + <nl> + / / Needed for backward compatibility <nl> + if ( ! kafka_settings - > input_format_skip_unknown_fields . changed ) <nl> + { <nl> + / / Always skip unknown fields regardless of the context ( JSON or TSKV ) <nl> + kafka_settings - > input_format_skip_unknown_fields = true ; <nl> + } <nl> + <nl> + if ( ! kafka_settings - > input_format_allow_errors_ratio . changed ) <nl> + { <nl> + kafka_settings - > input_format_allow_errors_ratio = 0 . ; <nl> + } <nl> + <nl> + if ( ! kafka_settings - > input_format_allow_errors_num . changed ) <nl> + { <nl> + kafka_settings - > input_format_allow_errors_num = kafka_settings - > kafka_skip_broken_messages . value ; <nl> + } <nl> + <nl> + if ( ! schema_name . empty ( ) ) <nl> + changes . emplace_back ( " format_schema " , schema_name ) ; <nl> + <nl> + for ( auto it = kafka_settings - > begin ( ) ; it ! = kafka_settings - > end ( ) ; + + it ) <nl> + { <nl> + if ( it - > isChanged ( ) & & it - > getName ( ) . toString ( ) . rfind ( " kafka_ " , 0 ) = = std : : string : : npos ) <nl> + { <nl> + changes . emplace_back ( it - > getName ( ) . toString ( ) , it - > getValueAsString ( ) ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + Names StorageKafka : : parseTopics ( String topic_list ) <nl> + { <nl> + Names topics_ ; <nl> + boost : : split ( topics_ , topic_list , [ ] ( char c ) { return c = = ' , ' ; } ) ; <nl> + for ( String & topic : topics_ ) <nl> + { <nl> + boost : : trim ( topic ) ; <nl> + } <nl> + return topics_ ; <nl> } <nl> <nl> String StorageKafka : : getDefaultClientId ( const StorageID & table_id_ ) <nl> ConsumerBufferPtr StorageKafka : : popReadBuffer ( std : : chrono : : milliseconds timeout ) <nl> return buffer ; <nl> } <nl> <nl> + void StorageKafka : : adjustContext ( Context & context ) <nl> + { <nl> + context . applySettingsChanges ( changes ) ; <nl> + } <nl> + <nl> <nl> ProducerBufferPtr StorageKafka : : createWriteBuffer ( const Block & header ) <nl> { <nl> ConsumerBufferPtr StorageKafka : : createReadBuffer ( const size_t consumer_number ) <nl> auto consumer = std : : make_shared < cppkafka : : Consumer > ( conf ) ; <nl> consumer - > set_destroy_flags ( RD_KAFKA_DESTROY_F_NO_CONSUMER_CLOSE ) ; <nl> <nl> - / / Limit the number of batched messages to allow early cancellations <nl> - const Settings & settings = global_context . getSettingsRef ( ) ; <nl> - size_t batch_size = max_block_size ; <nl> + / / / NOTE : we pass | stream_cancelled | by reference here , so the buffers should not outlive the storage . <nl> + return std : : make_shared < ReadBufferFromKafkaConsumer > ( consumer , log , getPollMaxBatchSize ( ) , getPollTimeout ( ) , intermediate_commit , stream_cancelled , getTopics ( ) ) ; <nl> + } <nl> + <nl> + size_t StorageKafka : : getMaxBlockSize ( ) const <nl> + { <nl> + size_t block_size = kafka_settings - > kafka_max_block_size . value ; <nl> + if ( ! block_size ) <nl> + { <nl> + block_size = global_context . getSettingsRef ( ) . max_insert_block_size . value / num_consumers ; <nl> + } <nl> + return block_size ; <nl> + } <nl> + <nl> + size_t StorageKafka : : getPollMaxBatchSize ( ) const <nl> + { <nl> + size_t batch_size = kafka_settings - > kafka_poll_max_batch_size . value ; <nl> + <nl> if ( ! batch_size ) <nl> - batch_size = settings . max_block_size . value ; <nl> - size_t poll_timeout = settings . stream_poll_timeout_ms . totalMilliseconds ( ) ; <nl> + { <nl> + batch_size = global_context . getSettingsRef ( ) . max_block_size . value ; <nl> + } <nl> + return std : : min ( batch_size , getMaxBlockSize ( ) ) ; <nl> + } <nl> <nl> - / / / NOTE : we pass | stream_cancelled | by reference here , so the buffers should not outlive the storage . <nl> - return std : : make_shared < ReadBufferFromKafkaConsumer > ( consumer , log , batch_size , poll_timeout , intermediate_commit , stream_cancelled , getTopics ( ) ) ; <nl> + size_t StorageKafka : : getPollTimeout ( ) const <nl> + { <nl> + size_t poll_timeout = kafka_settings - > kafka_poll_timeout_ms . totalMilliseconds ( ) ; <nl> + <nl> + if ( ! poll_timeout ) <nl> + { <nl> + poll_timeout = global_context . getSettingsRef ( ) . stream_poll_timeout_ms . totalMilliseconds ( ) ; <nl> + } <nl> + <nl> + return poll_timeout ; <nl> + } <nl> + <nl> + <nl> + size_t StorageKafka : : getFlushTimeout ( ) const <nl> + { <nl> + size_t flush_timeout = kafka_settings - > kafka_flush_interval_ms . totalMilliseconds ( ) ; <nl> + <nl> + if ( ! flush_timeout ) <nl> + { <nl> + flush_timeout = global_context . getSettingsRef ( ) . stream_flush_interval_ms . totalMilliseconds ( ) ; <nl> + } <nl> + <nl> + return flush_timeout ; <nl> } <nl> <nl> <nl> bool StorageKafka : : streamToViews ( ) <nl> auto insert = std : : make_shared < ASTInsertQuery > ( ) ; <nl> insert - > table_id = table_id ; <nl> <nl> - const Settings & settings = global_context . getSettingsRef ( ) ; <nl> - size_t block_size = max_block_size ; <nl> - if ( block_size = = 0 ) <nl> - block_size = settings . max_block_size ; <nl> + size_t block_size = getMaxBlockSize ( ) ; <nl> <nl> / / Create a stream for each consumer and join them in a union stream <nl> / / Only insert into dependent views and expect that input blocks contain virtual columns <nl> bool StorageKafka : : streamToViews ( ) <nl> / / Create a stream for each consumer and join them in a union stream <nl> BlockInputStreams streams ; <nl> streams . reserve ( num_created_consumers ) ; <nl> + <nl> for ( size_t i = 0 ; i < num_created_consumers ; + + i ) <nl> { <nl> auto stream <nl> bool StorageKafka : : streamToViews ( ) <nl> <nl> / / Limit read batch to maximum block size to allow DDL <nl> IBlockInputStream : : LocalLimits limits ; <nl> - limits . speed_limits . max_execution_time = settings . stream_flush_interval_ms ; <nl> + limits . speed_limits . max_execution_time = getFlushTimeout ( ) ; <nl> limits . timeout_overflow_mode = OverflowMode : : BREAK ; <nl> stream - > setLimits ( limits ) ; <nl> } <nl> void registerStorageKafka ( StorageFactory & factory ) <nl> size_t args_count = engine_args . size ( ) ; <nl> bool has_settings = args . storage_def - > settings ; <nl> <nl> - KafkaSettings kafka_settings ; <nl> + auto kafka_settings = std : : make_unique < KafkaSettings > ( ) ; <nl> if ( has_settings ) <nl> { <nl> - kafka_settings . loadFromQuery ( * args . storage_def ) ; <nl> + kafka_settings - > loadFromQuery ( * args . storage_def ) ; <nl> } <nl> <nl> + / / Check arguments and settings <nl> + # define CHECK_KAFKA_STORAGE_ARGUMENT ( ARG_NUM , PAR_NAME , EVAL ) \ <nl> + / * One of the four required arguments is not specified * / \ <nl> + if ( args_count < ( ARG_NUM ) & & ( ARG_NUM ) < = 4 & & \ <nl> + ! kafka_settings - > PAR_NAME . changed ) \ <nl> + { \ <nl> + throw Exception ( \ <nl> + " Required parameter ' " # PAR_NAME " ' " \ <nl> + " for storage Kafka not specified " , \ <nl> + ErrorCodes : : NUMBER_OF_ARGUMENTS_DOESNT_MATCH ) ; \ <nl> + } \ <nl> + if ( args_count > = ( ARG_NUM ) ) \ <nl> + { \ <nl> + / * The same argument is given in two places * / \ <nl> + if ( has_settings & & \ <nl> + kafka_settings - > PAR_NAME . changed ) \ <nl> + { \ <nl> + throw Exception ( \ <nl> + " The argument № " # ARG_NUM " of storage Kafka " \ <nl> + " and the parameter ' " # PAR_NAME " ' " \ <nl> + " in SETTINGS cannot be specified at the same time " , \ <nl> + ErrorCodes : : BAD_ARGUMENTS ) ; \ <nl> + } \ <nl> + / * move engine args to settings * / \ <nl> + else \ <nl> + { \ <nl> + if ( ( EVAL ) = = 1 ) \ <nl> + { \ <nl> + engine_args [ ARG_NUM - 1 ] = \ <nl> + evaluateConstantExpressionAsLiteral ( \ <nl> + engine_args [ ARG_NUM - 1 ] , \ <nl> + args . local_context ) ; \ <nl> + } \ <nl> + if ( ( EVAL ) = = 2 ) \ <nl> + { \ <nl> + engine_args [ ARG_NUM - 1 ] = \ <nl> + evaluateConstantExpressionOrIdentifierAsLiteral ( \ <nl> + engine_args [ ARG_NUM - 1 ] , \ <nl> + args . local_context ) ; \ <nl> + } \ <nl> + kafka_settings - > PAR_NAME . set ( \ <nl> + engine_args [ ARG_NUM - 1 ] - > as < ASTLiteral & > ( ) . value ) ; \ <nl> + } \ <nl> + } <nl> + <nl> / * * Arguments of engine is following : <nl> * - Kafka broker list <nl> * - List of topics <nl> * - Group ID ( may be a constaint expression with a string result ) <nl> - * - Client ID <nl> * - Message format ( string ) <nl> * - Row delimiter <nl> * - Schema ( optional , if the format supports it ) <nl> void registerStorageKafka ( StorageFactory & factory ) <nl> * - Do intermediate commits when the batch consumed and handled <nl> * / <nl> <nl> - / / Check arguments and settings <nl> - # define CHECK_KAFKA_STORAGE_ARGUMENT ( ARG_NUM , PAR_NAME ) \ <nl> - / * One of the four required arguments is not specified * / \ <nl> - if ( args_count < ( ARG_NUM ) & & ( ARG_NUM ) < = 4 & & \ <nl> - ! kafka_settings . PAR_NAME . changed ) \ <nl> - { \ <nl> - throw Exception ( \ <nl> - " Required parameter ' " # PAR_NAME " ' " \ <nl> - " for storage Kafka not specified " , \ <nl> - ErrorCodes : : NUMBER_OF_ARGUMENTS_DOESNT_MATCH ) ; \ <nl> - } \ <nl> - / * The same argument is given in two places * / \ <nl> - if ( has_settings & & \ <nl> - kafka_settings . PAR_NAME . changed & & \ <nl> - args_count > = ( ARG_NUM ) ) \ <nl> - { \ <nl> - throw Exception ( \ <nl> - " The argument № " # ARG_NUM " of storage Kafka " \ <nl> - " and the parameter ' " # PAR_NAME " ' " \ <nl> - " in SETTINGS cannot be specified at the same time " , \ <nl> - ErrorCodes : : BAD_ARGUMENTS ) ; \ <nl> - } <nl> - <nl> - CHECK_KAFKA_STORAGE_ARGUMENT ( 1 , kafka_broker_list ) <nl> - CHECK_KAFKA_STORAGE_ARGUMENT ( 2 , kafka_topic_list ) <nl> - CHECK_KAFKA_STORAGE_ARGUMENT ( 3 , kafka_group_name ) <nl> - CHECK_KAFKA_STORAGE_ARGUMENT ( 4 , kafka_format ) <nl> - CHECK_KAFKA_STORAGE_ARGUMENT ( 5 , kafka_row_delimiter ) <nl> - CHECK_KAFKA_STORAGE_ARGUMENT ( 6 , kafka_schema ) <nl> - CHECK_KAFKA_STORAGE_ARGUMENT ( 7 , kafka_num_consumers ) <nl> - CHECK_KAFKA_STORAGE_ARGUMENT ( 8 , kafka_max_block_size ) <nl> - CHECK_KAFKA_STORAGE_ARGUMENT ( 9 , kafka_skip_broken_messages ) <nl> - CHECK_KAFKA_STORAGE_ARGUMENT ( 10 , kafka_commit_every_batch ) <nl> + / * 0 = raw , 1 = evaluateConstantExpressionAsLiteral , 2 = evaluateConstantExpressionOrIdentifierAsLiteral * / <nl> + CHECK_KAFKA_STORAGE_ARGUMENT ( 1 , kafka_broker_list , 0 ) <nl> + CHECK_KAFKA_STORAGE_ARGUMENT ( 2 , kafka_topic_list , 1 ) <nl> + CHECK_KAFKA_STORAGE_ARGUMENT ( 3 , kafka_group_name , 2 ) <nl> + CHECK_KAFKA_STORAGE_ARGUMENT ( 4 , kafka_format , 2 ) <nl> + CHECK_KAFKA_STORAGE_ARGUMENT ( 5 , kafka_row_delimiter , 2 ) <nl> + CHECK_KAFKA_STORAGE_ARGUMENT ( 6 , kafka_schema , 2 ) <nl> + CHECK_KAFKA_STORAGE_ARGUMENT ( 7 , kafka_num_consumers , 0 ) <nl> + CHECK_KAFKA_STORAGE_ARGUMENT ( 8 , kafka_max_block_size , 0 ) <nl> + CHECK_KAFKA_STORAGE_ARGUMENT ( 9 , kafka_skip_broken_messages , 0 ) <nl> + CHECK_KAFKA_STORAGE_ARGUMENT ( 10 , kafka_commit_every_batch , 0 ) <nl> <nl> # undef CHECK_KAFKA_STORAGE_ARGUMENT <nl> <nl> - / / Get and check broker list <nl> - String brokers = kafka_settings . kafka_broker_list ; <nl> - if ( args_count > = 1 ) <nl> - { <nl> - const auto * ast = engine_args [ 0 ] - > as < ASTLiteral > ( ) ; <nl> - if ( ast & & ast - > value . getType ( ) = = Field : : Types : : String ) <nl> - { <nl> - brokers = safeGet < String > ( ast - > value ) ; <nl> - } <nl> - else <nl> - { <nl> - throw Exception ( String ( " Kafka broker list must be a string " ) , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> - } <nl> - } <nl> - <nl> - / / Get and check topic list <nl> - String topic_list = kafka_settings . kafka_topic_list . value ; <nl> - if ( args_count > = 2 ) <nl> - { <nl> - engine_args [ 1 ] = evaluateConstantExpressionAsLiteral ( engine_args [ 1 ] , args . local_context ) ; <nl> - topic_list = engine_args [ 1 ] - > as < ASTLiteral & > ( ) . value . safeGet < String > ( ) ; <nl> - } <nl> - <nl> - Names topics ; <nl> - boost : : split ( topics , topic_list , [ ] ( char c ) { return c = = ' , ' ; } ) ; <nl> - for ( String & topic : topics ) <nl> - { <nl> - boost : : trim ( topic ) ; <nl> - } <nl> - <nl> - / / Get and check group name <nl> - String group = kafka_settings . kafka_group_name . value ; <nl> - if ( args_count > = 3 ) <nl> - { <nl> - engine_args [ 2 ] = evaluateConstantExpressionOrIdentifierAsLiteral ( engine_args [ 2 ] , args . local_context ) ; <nl> - group = engine_args [ 2 ] - > as < ASTLiteral & > ( ) . value . safeGet < String > ( ) ; <nl> - } <nl> - <nl> - / / Get and check message format name <nl> - String format = kafka_settings . kafka_format . value ; <nl> - if ( args_count > = 4 ) <nl> - { <nl> - engine_args [ 3 ] = evaluateConstantExpressionOrIdentifierAsLiteral ( engine_args [ 3 ] , args . local_context ) ; <nl> - <nl> - const auto * ast = engine_args [ 3 ] - > as < ASTLiteral > ( ) ; <nl> - if ( ast & & ast - > value . getType ( ) = = Field : : Types : : String ) <nl> - { <nl> - format = safeGet < String > ( ast - > value ) ; <nl> - } <nl> - else <nl> - { <nl> - throw Exception ( " Format must be a string " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> - } <nl> - } <nl> - <nl> - / / Parse row delimiter ( optional ) <nl> - char row_delimiter = kafka_settings . kafka_row_delimiter ; <nl> - if ( args_count > = 5 ) <nl> - { <nl> - engine_args [ 4 ] = evaluateConstantExpressionOrIdentifierAsLiteral ( engine_args [ 4 ] , args . local_context ) ; <nl> - <nl> - const auto * ast = engine_args [ 4 ] - > as < ASTLiteral > ( ) ; <nl> - String arg ; <nl> - if ( ast & & ast - > value . getType ( ) = = Field : : Types : : String ) <nl> - { <nl> - arg = safeGet < String > ( ast - > value ) ; <nl> - } <nl> - else <nl> - { <nl> - throw Exception ( " Row delimiter must be a char " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> - } <nl> - if ( arg . size ( ) > 1 ) <nl> - { <nl> - throw Exception ( " Row delimiter must be a char " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> - } <nl> - else if ( arg . empty ( ) ) <nl> - { <nl> - row_delimiter = ' \ 0 ' ; <nl> - } <nl> - else <nl> - { <nl> - row_delimiter = arg [ 0 ] ; <nl> - } <nl> - } <nl> + auto kafka_num_consumers = kafka_settings - > kafka_num_consumers . value ; <nl> <nl> - / / Parse format schema if supported ( optional ) <nl> - String schema = kafka_settings . kafka_schema . value ; <nl> - if ( args_count > = 6 ) <nl> + if ( kafka_num_consumers > 16 ) <nl> { <nl> - engine_args [ 5 ] = evaluateConstantExpressionOrIdentifierAsLiteral ( engine_args [ 5 ] , args . local_context ) ; <nl> - <nl> - const auto * ast = engine_args [ 5 ] - > as < ASTLiteral > ( ) ; <nl> - if ( ast & & ast - > value . getType ( ) = = Field : : Types : : String ) <nl> - { <nl> - schema = safeGet < String > ( ast - > value ) ; <nl> - } <nl> - else <nl> - { <nl> - throw Exception ( " Format schema must be a string " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> - } <nl> - } <nl> - <nl> - / / Parse number of consumers ( optional ) <nl> - UInt64 num_consumers = kafka_settings . kafka_num_consumers ; <nl> - if ( args_count > = 7 ) <nl> - { <nl> - const auto * ast = engine_args [ 6 ] - > as < ASTLiteral > ( ) ; <nl> - if ( ast & & ast - > value . getType ( ) = = Field : : Types : : UInt64 ) <nl> - { <nl> - num_consumers = safeGet < UInt64 > ( ast - > value ) ; <nl> - } <nl> - else <nl> - { <nl> - throw Exception ( " Number of consumers must be a positive integer " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> - } <nl> - } <nl> - <nl> - / / Parse max block size ( optional ) <nl> - UInt64 max_block_size = static_cast < size_t > ( kafka_settings . kafka_max_block_size ) ; <nl> - if ( args_count > = 8 ) <nl> - { <nl> - const auto * ast = engine_args [ 7 ] - > as < ASTLiteral > ( ) ; <nl> - if ( ast & & ast - > value . getType ( ) = = Field : : Types : : UInt64 ) <nl> - { <nl> - max_block_size = static_cast < size_t > ( safeGet < UInt64 > ( ast - > value ) ) ; <nl> - } <nl> - else <nl> - { <nl> - / / TODO : no check if the integer is really positive <nl> - throw Exception ( " Maximum block size must be a positive integer " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> - } <nl> - } <nl> - <nl> - size_t skip_broken = static_cast < size_t > ( kafka_settings . kafka_skip_broken_messages ) ; <nl> - if ( args_count > = 9 ) <nl> - { <nl> - const auto * ast = engine_args [ 8 ] - > as < ASTLiteral > ( ) ; <nl> - if ( ast & & ast - > value . getType ( ) = = Field : : Types : : UInt64 ) <nl> - { <nl> - skip_broken = static_cast < size_t > ( safeGet < UInt64 > ( ast - > value ) ) ; <nl> - } <nl> - else <nl> - { <nl> - throw Exception ( " Number of broken messages to skip must be a non - negative integer " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> - } <nl> + throw Exception ( " Number of consumers can not be bigger than 16 " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> } <nl> - <nl> - bool intermediate_commit = static_cast < bool > ( kafka_settings . kafka_commit_every_batch ) ; <nl> - if ( args_count > = 10 ) <nl> + else if ( kafka_num_consumers < 1 ) <nl> { <nl> - const auto * ast = engine_args [ 9 ] - > as < ASTLiteral > ( ) ; <nl> - if ( ast & & ast - > value . getType ( ) = = Field : : Types : : UInt64 ) <nl> - { <nl> - intermediate_commit = static_cast < bool > ( safeGet < UInt64 > ( ast - > value ) ) ; <nl> - } <nl> - else <nl> - { <nl> - throw Exception ( " Flag for committing every batch must be 0 or 1 " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> - } <nl> + throw Exception ( " Number of consumers can not be lower than 1 " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> } <nl> <nl> - / / Get and check client id <nl> - String client_id = kafka_settings . kafka_client_id . value ; <nl> - <nl> - return StorageKafka : : create ( <nl> - args . table_id , args . context , args . columns , <nl> - brokers , group , client_id , topics , format , row_delimiter , schema , num_consumers , max_block_size , skip_broken , intermediate_commit ) ; <nl> + return StorageKafka : : create ( args . table_id , args . context , args . columns , std : : move ( kafka_settings ) ) ; <nl> } ; <nl> <nl> factory . registerStorage ( " Kafka " , creator_fn , StorageFactory : : StorageFeatures { . supports_settings = true , } ) ; <nl> mmm a / src / Storages / Kafka / StorageKafka . h <nl> ppp b / src / Storages / Kafka / StorageKafka . h <nl> <nl> # include < Core / BackgroundSchedulePool . h > <nl> # include < Storages / IStorage . h > <nl> # include < Storages / Kafka / Buffer_fwd . h > <nl> + # include < Storages / Kafka / KafkaSettings . h > <nl> # include < Interpreters / Context . h > <nl> <nl> # include < Poco / Semaphore . h > <nl> class StorageKafka final : public ext : : shared_ptr_helper < StorageKafka > , public I <nl> <nl> const auto & getTopics ( ) const { return topics ; } <nl> const auto & getFormatName ( ) const { return format_name ; } <nl> - const auto & getSchemaName ( ) const { return schema_name ; } <nl> - const auto & skipBroken ( ) const { return skip_broken ; } <nl> + void adjustContext ( Context & context ) ; <nl> + <nl> <nl> NamesAndTypesList getVirtuals ( ) const override ; <nl> protected : <nl> class StorageKafka final : public ext : : shared_ptr_helper < StorageKafka > , public I <nl> const StorageID & table_id_ , <nl> Context & context_ , <nl> const ColumnsDescription & columns_ , <nl> - const String & brokers_ , <nl> - const String & group_ , <nl> - const String & client_id_ , <nl> - const Names & topics_ , <nl> - const String & format_name_ , <nl> - char row_delimiter_ , <nl> - const String & schema_name_ , <nl> - size_t num_consumers_ , <nl> - UInt64 max_block_size_ , <nl> - size_t skip_broken , <nl> - bool intermediate_commit_ ) ; <nl> + std : : unique_ptr < KafkaSettings > kafka_settings_ ) ; <nl> <nl> private : <nl> / / Configuration and state <nl> Context global_context ; <nl> Context kafka_context ; <nl> + std : : unique_ptr < KafkaSettings > kafka_settings ; <nl> Names topics ; <nl> const String brokers ; <nl> const String group ; <nl> const String client_id ; <nl> const String format_name ; <nl> + SettingsChanges changes ; <nl> + <nl> char row_delimiter ; / / / optional row delimiter for generating char delimited stream in order to make various input stream parsers happy . <nl> const String schema_name ; <nl> size_t num_consumers ; / / / total number of consumers <nl> - UInt64 max_block_size ; / / / maximum block size for insertion into this table <nl> <nl> / / / Can differ from num_consumers in case of exception in startup ( ) ( or if startup ( ) hasn ' t been called ) . <nl> / / / In this case we still need to be able to shutdown ( ) properly . <nl> class StorageKafka final : public ext : : shared_ptr_helper < StorageKafka > , public I <nl> ConsumerBufferPtr createReadBuffer ( const size_t consumer_number ) ; <nl> <nl> / / Update Kafka configuration with values from CH user configuration . <nl> - void updateConfiguration ( cppkafka : : Configuration & conf ) ; <nl> <nl> + void updateConfiguration ( cppkafka : : Configuration & conf ) ; <nl> void threadFunc ( ) ; <nl> + <nl> + size_t getPollMaxBatchSize ( ) const ; <nl> + size_t getMaxBlockSize ( ) const ; <nl> + size_t getPollTimeout ( ) const ; <nl> + size_t getFlushTimeout ( ) const ; <nl> + <nl> + <nl> + static Names parseTopics ( String topic_list ) ; <nl> static String getDefaultClientId ( const StorageID & table_id_ ) ; <nl> + <nl> bool streamToViews ( ) ; <nl> bool checkDependencies ( const StorageID & table_id ) ; <nl> } ; <nl>
Support for all format settings in Kafka , expose some setting on table level , better defaults .
ClickHouse/ClickHouse
4956ade67d042929e1ce8a811bf98304ae47d1f3
2020-06-03T17:01:41Z
mmm a / modules / java / android_test / src / org / opencv / test / core / MatTest . java <nl> ppp b / modules / java / android_test / src / org / opencv / test / core / MatTest . java <nl> public void testGetIntInt ( ) { <nl> } <nl> <nl> public void testGetIntIntByteArray ( ) { <nl> - fail ( " Not yet implemented " ) ; <nl> + Mat m = new Mat ( 5 , 5 , CvType . CV_8UC3 , new Scalar ( 1 , 2 , 3 ) ) ; <nl> + byte [ ] goodData = new byte [ 9 ] ; <nl> + byte [ ] badData = new byte [ 7 ] ; <nl> + m . get ( 1 , 1 , goodData ) ; <nl> + try { <nl> + m . get ( 2 , 2 , badData ) ; <nl> + fail ( " Expected UnsupportedOperationException ( data . length % CvType . channels ( t ) ! = 0 ) " ) ; <nl> + } catch ( UnsupportedOperationException e ) { <nl> + / / expected <nl> + } <nl> } <nl> <nl> public void testGetIntIntDoubleArray ( ) { <nl> public void testPutIntIntByteArray ( ) { <nl> } <nl> <nl> public void testPutIntIntDoubleArray ( ) { <nl> - fail ( " Not yet implemented " ) ; <nl> + Mat m = new Mat ( 5 , 5 , CvType . CV_8UC3 ) ; <nl> + m . put ( 1 , 1 , 10 , 20 , 30 , 40 , 50 , 60 ) ; <nl> + try { <nl> + m . put ( 2 , 2 , 11 , 22 , 33 , 44 , 55 ) ; <nl> + fail ( " Expected UnsupportedOperationException ( data . length % CvType . channels ( t ) ! = 0 ) " ) ; <nl> + } catch ( UnsupportedOperationException e ) { <nl> + / / expected <nl> + } <nl> } <nl> <nl> public void testPutIntIntFloatArray ( ) { <nl> mmm a / modules / java / src / java / core + Mat . java <nl> ppp b / modules / java / src / java / core + Mat . java <nl> public String dump ( ) { <nl> <nl> / / javadoc : Mat : : put ( row , col , data ) <nl> public int put ( int row , int col , double . . . data ) { <nl> + int t = type ( ) ; <nl> + if ( data = = null | | data . length % CvType . channels ( t ) ! = 0 ) <nl> + throw new java . lang . UnsupportedOperationException ( <nl> + " Provided data element number ( " + <nl> + ( data = = null ? 0 : data . length ) + <nl> + " ) should be multiple of the Mat channels count ( " + <nl> + CvType . channels ( t ) + " ) " ) ; <nl> return nPutD ( nativeObj , row , col , data . length , data ) ; <nl> } <nl> <nl> / / javadoc : Mat : : put ( row , col , data ) <nl> public int put ( int row , int col , float [ ] data ) { <nl> int t = type ( ) ; <nl> + if ( data = = null | | data . length % CvType . channels ( t ) ! = 0 ) <nl> + throw new java . lang . UnsupportedOperationException ( <nl> + " Provided data element number ( " + <nl> + ( data = = null ? 0 : data . length ) + <nl> + " ) should be multiple of the Mat channels count ( " + <nl> + CvType . channels ( t ) + " ) " ) ; <nl> if ( CvType . depth ( t ) = = CvType . CV_32F ) { <nl> return nPutF ( nativeObj , row , col , data . length , data ) ; <nl> } <nl> public int put ( int row , int col , float [ ] data ) { <nl> / / javadoc : Mat : : put ( row , col , data ) <nl> public int put ( int row , int col , int [ ] data ) { <nl> int t = type ( ) ; <nl> + if ( data = = null | | data . length % CvType . channels ( t ) ! = 0 ) <nl> + throw new java . lang . UnsupportedOperationException ( <nl> + " Provided data element number ( " + <nl> + ( data = = null ? 0 : data . length ) + <nl> + " ) should be multiple of the Mat channels count ( " + <nl> + CvType . channels ( t ) + " ) " ) ; <nl> if ( CvType . depth ( t ) = = CvType . CV_32S ) { <nl> return nPutI ( nativeObj , row , col , data . length , data ) ; <nl> } <nl> public int put ( int row , int col , int [ ] data ) { <nl> / / javadoc : Mat : : put ( row , col , data ) <nl> public int put ( int row , int col , short [ ] data ) { <nl> int t = type ( ) ; <nl> + if ( data = = null | | data . length % CvType . channels ( t ) ! = 0 ) <nl> + throw new java . lang . UnsupportedOperationException ( <nl> + " Provided data element number ( " + <nl> + ( data = = null ? 0 : data . length ) + <nl> + " ) should be multiple of the Mat channels count ( " + <nl> + CvType . channels ( t ) + " ) " ) ; <nl> if ( CvType . depth ( t ) = = CvType . CV_16U | | CvType . depth ( t ) = = CvType . CV_16S ) { <nl> return nPutS ( nativeObj , row , col , data . length , data ) ; <nl> } <nl> public int put ( int row , int col , short [ ] data ) { <nl> / / javadoc : Mat : : put ( row , col , data ) <nl> public int put ( int row , int col , byte [ ] data ) { <nl> int t = type ( ) ; <nl> + if ( data = = null | | data . length % CvType . channels ( t ) ! = 0 ) <nl> + throw new java . lang . UnsupportedOperationException ( <nl> + " Provided data element number ( " + <nl> + ( data = = null ? 0 : data . length ) + <nl> + " ) should be multiple of the Mat channels count ( " + <nl> + CvType . channels ( t ) + " ) " ) ; <nl> if ( CvType . depth ( t ) = = CvType . CV_8U | | CvType . depth ( t ) = = CvType . CV_8S ) { <nl> return nPutB ( nativeObj , row , col , data . length , data ) ; <nl> } <nl> public int put ( int row , int col , byte [ ] data ) { <nl> / / javadoc : Mat : : get ( row , col , data ) <nl> public int get ( int row , int col , byte [ ] data ) { <nl> int t = type ( ) ; <nl> + if ( data = = null | | data . length % CvType . channels ( t ) ! = 0 ) <nl> + throw new java . lang . UnsupportedOperationException ( <nl> + " Provided data element number ( " + <nl> + ( data = = null ? 0 : data . length ) + <nl> + " ) should be multiple of the Mat channels count ( " + <nl> + CvType . channels ( t ) + " ) " ) ; <nl> if ( CvType . depth ( t ) = = CvType . CV_8U | | CvType . depth ( t ) = = CvType . CV_8S ) { <nl> return nGetB ( nativeObj , row , col , data . length , data ) ; <nl> } <nl> public int get ( int row , int col , byte [ ] data ) { <nl> / / javadoc : Mat : : get ( row , col , data ) <nl> public int get ( int row , int col , short [ ] data ) { <nl> int t = type ( ) ; <nl> + if ( data = = null | | data . length % CvType . channels ( t ) ! = 0 ) <nl> + throw new java . lang . UnsupportedOperationException ( <nl> + " Provided data element number ( " + <nl> + ( data = = null ? 0 : data . length ) + <nl> + " ) should be multiple of the Mat channels count ( " + <nl> + CvType . channels ( t ) + " ) " ) ; <nl> if ( CvType . depth ( t ) = = CvType . CV_16U | | CvType . depth ( t ) = = CvType . CV_16S ) { <nl> return nGetS ( nativeObj , row , col , data . length , data ) ; <nl> } <nl> public int get ( int row , int col , short [ ] data ) { <nl> / / javadoc : Mat : : get ( row , col , data ) <nl> public int get ( int row , int col , int [ ] data ) { <nl> int t = type ( ) ; <nl> + if ( data = = null | | data . length % CvType . channels ( t ) ! = 0 ) <nl> + throw new java . lang . UnsupportedOperationException ( <nl> + " Provided data element number ( " + <nl> + ( data = = null ? 0 : data . length ) + <nl> + " ) should be multiple of the Mat channels count ( " + <nl> + CvType . channels ( t ) + " ) " ) ; <nl> if ( CvType . depth ( t ) = = CvType . CV_32S ) { <nl> return nGetI ( nativeObj , row , col , data . length , data ) ; <nl> } <nl> public int get ( int row , int col , int [ ] data ) { <nl> / / javadoc : Mat : : get ( row , col , data ) <nl> public int get ( int row , int col , float [ ] data ) { <nl> int t = type ( ) ; <nl> + if ( data = = null | | data . length % CvType . channels ( t ) ! = 0 ) <nl> + throw new java . lang . UnsupportedOperationException ( <nl> + " Provided data element number ( " + <nl> + ( data = = null ? 0 : data . length ) + <nl> + " ) should be multiple of the Mat channels count ( " + <nl> + CvType . channels ( t ) + " ) " ) ; <nl> if ( CvType . depth ( t ) = = CvType . CV_32F ) { <nl> return nGetF ( nativeObj , row , col , data . length , data ) ; <nl> } <nl> public int get ( int row , int col , float [ ] data ) { <nl> / / javadoc : Mat : : get ( row , col , data ) <nl> public int get ( int row , int col , double [ ] data ) { <nl> int t = type ( ) ; <nl> + if ( data = = null | | data . length % CvType . channels ( t ) ! = 0 ) <nl> + throw new java . lang . UnsupportedOperationException ( <nl> + " Provided data element number ( " + <nl> + ( data = = null ? 0 : data . length ) + <nl> + " ) should be multiple of the Mat channels count ( " + <nl> + CvType . channels ( t ) + " ) " ) ; <nl> if ( CvType . depth ( t ) = = CvType . CV_64F ) { <nl> return nGetD ( nativeObj , row , col , data . length , data ) ; <nl> } <nl>
Java API : ( per code review ) adding check ( data . length % CvType . channels ( t ) ! = 0 ) for Mat : : put / get , adding 2 tests for them
opencv/opencv
024482adac002e812e29bfe47314a4c25e64b3de
2011-08-04T11:45:48Z
mmm a / Marlin / src / config / examples / Creality / CR - 10mini / Configuration . h <nl> ppp b / Marlin / src / config / examples / Creality / CR - 10mini / Configuration . h <nl> <nl> * Override with M92 <nl> * X , Y , Z , E0 [ , E1 [ , E2 [ , E3 [ , E4 [ , E5 ] ] ] ] ] <nl> * / <nl> - # define DEFAULT_AXIS_STEPS_PER_UNIT { 79 . 60 , 80 , 400 , 229 . 4 } <nl> + # define DEFAULT_AXIS_STEPS_PER_UNIT { 79 . 60 , 80 , 400 , 95 } <nl> <nl> / * * <nl> * Default Max Feed Rate ( mm / s ) <nl>
C10mini E steps of 95
MarlinFirmware/Marlin
8d271f20febf09531ceb6da53beec2d034e669be
2019-02-10T20:23:05Z
mmm a / tensorflow / python / autograph / operators / py_builtins . py <nl> ppp b / tensorflow / python / autograph / operators / py_builtins . py <nl> def _tf_sorted ( iterable , key , reverse ) : <nl> direction = ' DESCENDING ' <nl> if key is not UNSPECIFIED : <nl> mapped = parallel_ops . vectorized_map ( key , iterable ) <nl> + if mapped . shape . rank is not None and mapped . shape . rank ! = 1 : <nl> + raise ValueError ( ' sort only supports only 1D tensors ' ) <nl> with ops . control_dependencies ( <nl> - [ check_ops . assert_rank_v2 ( mapped , 1 , ' only support 1 - D tensor ' ) ] ) : <nl> + [ check_ops . assert_rank_v2 ( mapped , 1 , ' sort only supports only 1D tensors ' ) ] ) : <nl> order = sort_ops . argsort ( mapped , direction = direction ) <nl> return array_ops . gather_v2 ( iterable , order ) <nl> + if iterable . shape . rank is not None and iterable . shape . rank ! = 1 : <nl> + raise ValueError ( ' sort only supports only 1D tensors ' ) <nl> with ops . control_dependencies ( <nl> - [ check_ops . assert_rank_v2 ( iterable , 1 , ' only support 1 - D tensor ' ) ] ) : <nl> + [ check_ops . assert_rank_v2 ( iterable , 1 , ' sort only supports only 1D tensors ' ) ] ) : <nl> return sort_ops . sort ( iterable , direction = direction ) <nl> <nl> <nl>
add an extra check in case the rank is static
tensorflow/tensorflow
bf0b5b619d633fcff14cc11243297537e83d77d2
2020-02-21T02:32:05Z
mmm a / tensorflow / core / kernels / control_flow_ops . cc <nl> ppp b / tensorflow / core / kernels / control_flow_ops . cc <nl> REGISTER_GPU_SWITCH ( uint64 ) ; <nl> TF_CALL_variant ( REGISTER_GPU_SWITCH ) ; <nl> TF_CALL_uint32 ( REGISTER_GPU_SWITCH ) ; <nl> TF_CALL_uint32 ( REGISTER_GPU_REF_SWITCH ) ; <nl> - TF_CALL_bool ( REGISTER_GPU_SWITCH ) ; <nl> - TF_CALL_bool ( REGISTER_GPU_REF_SWITCH ) ; <nl> <nl> # undef REGISTER_CPU_SWITCH <nl> # undef REGISTER_CPU_REF_SWITCH <nl> # undef REGISTER_GPU_SWITCH <nl> # undef REGISTER_GPU_REF_SWITCH <nl> <nl> - / / Special GPU kernels for int32 , string & resource handles . Requiring all <nl> - / / inputs and outputs to be in host memory . <nl> - / / TODO ( b / 25387198 ) : Also enable int32 in device memory . <nl> + / / Special GPU kernels for int32 and string . <nl> + / / TODO ( b / 25387198 ) : Also enable int32 in device memory . This kernel <nl> + / / registration requires all int32 inputs and outputs to be in host memory . <nl> # define REGISTER_GPU_HOST_KERNEL ( type ) \ <nl> REGISTER_KERNEL_BUILDER ( Name ( " Switch " ) \ <nl> . Device ( DEVICE_GPU ) \ <nl> TF_CALL_bool ( REGISTER_GPU_REF_SWITCH ) ; <nl> <nl> REGISTER_GPU_HOST_KERNEL ( int32 ) ; <nl> REGISTER_GPU_HOST_REF_KERNEL ( int32 ) ; <nl> + REGISTER_GPU_HOST_KERNEL ( bool ) ; <nl> + REGISTER_GPU_HOST_REF_KERNEL ( bool ) ; <nl> REGISTER_GPU_HOST_KERNEL ( tstring ) ; <nl> REGISTER_GPU_HOST_REF_KERNEL ( tstring ) ; <nl> REGISTER_GPU_HOST_KERNEL ( ResourceHandle ) ; <nl> mmm a / tensorflow / core / kernels / variable_ops . cc <nl> ppp b / tensorflow / core / kernels / variable_ops . cc <nl> TF_CALL_GPU_NUMBER_TYPES_NO_HALF ( REGISTER_SYCL_KERNEL ) ; <nl> <nl> TF_CALL_int64 ( REGISTER_GPU_KERNELS ) ; <nl> TF_CALL_uint32 ( REGISTER_GPU_KERNELS ) ; <nl> - TF_CALL_GPU_ALL_TYPES ( REGISTER_GPU_KERNELS ) ; <nl> + TF_CALL_GPU_NUMBER_TYPES ( REGISTER_GPU_KERNELS ) ; <nl> + TF_CALL_COMPLEX_TYPES ( REGISTER_GPU_KERNELS ) ; <nl> # undef REGISTER_GPU_KERNELS <nl> # endif / / GOOGLE_CUDA | | TENSORFLOW_USE_ROCM <nl> <nl> mmm a / tensorflow / python / debug / lib / debug_graph_reconstruction_test . py <nl> ppp b / tensorflow / python / debug / lib / debug_graph_reconstruction_test . py <nl> def _graphDefWithoutBlacklistedNodes ( self , graph_def ) : <nl> for attr_key in new_node . attr : <nl> if attr_key = = " parallel_iterations " : <nl> new_node . attr [ attr_key ] . i = 1 <nl> - elif new_node . op = = " Switch " or new_node . op = = " Identity " : <nl> - # We don ' t check the inputs to Switch or Identity ops as their inputs <nl> - # may be Send / Recv nodes . <nl> + elif new_node . op = = " Switch " : <nl> + # We don ' t check the inputs to Switch ops as their inputs may be <nl> + # Send / Recv nodes . <nl> del new_node . input [ : ] <nl> <nl> return output_graph_def <nl> mmm a / tensorflow / python / ops / control_flow_ops_test . py <nl> ppp b / tensorflow / python / ops / control_flow_ops_test . py <nl> def testCondFalseLegacy ( self ) : <nl> fn2 = lambda : math_ops . add ( y , 23 ) ) <nl> self . assertEquals ( self . evaluate ( z ) , 24 ) <nl> <nl> - @ test_util . run_v1_only ( " Exercises Ref variables " ) <nl> + @ test_util . run_deprecated_v1 <nl> def testCondModifyBoolPred ( self ) : <nl> - # We want to use the GPU here because we want to ensure that we can update <nl> - # a boolean ref variable on the GPU . <nl> + # This test in particular used to fail only when running in GPU , hence <nl> + # use_gpu = True . <nl> with test_util . use_gpu ( ) : <nl> bool_var = variable_scope . get_variable ( <nl> " bool_var " , dtype = dtypes . bool , initializer = True ) <nl>
* * * Reason for rollback * * *
tensorflow/tensorflow
b5bb616121f1805c5ff5391daf00c86b6bcad1ae
2020-06-19T04:11:16Z
mmm a / fdbserver / DataDistribution . actor . cpp <nl> ppp b / fdbserver / DataDistribution . actor . cpp <nl> <nl> # include " fdbrpc / Replication . h " <nl> # include " flow / UnitTest . h " <nl> # include " flow / actorcompiler . h " / / This must be the last # include . <nl> + # include " . . / flow / Trace . h " <nl> <nl> class TCTeamInfo ; <nl> struct TCMachineInfo ; <nl> ACTOR Future < Void > waitForAllDataRemoved ( Database cx , UID serverID , Version add <nl> <nl> / / Wait for any change to the serverKeys for this server <nl> wait ( delay ( SERVER_KNOBS - > ALL_DATA_REMOVED_DELAY , TaskDataDistribution ) ) ; <nl> - / / tr . waitForChanges ( KeyRangeRef ( serverKeysPrefixFor ( serverID ) , <nl> - / / serverKeysPrefixFor ( serverID ) . toString ( ) + allKeys . end . toString ( ) ) ) ; <nl> tr . reset ( ) ; <nl> } catch ( Error & e ) { <nl> wait ( tr . onError ( e ) ) ; <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> std : : map < int , int > priority_teams ; <nl> std : : map < UID , Reference < TCServerInfo > > server_info ; <nl> <nl> - std : : map < Standalone < StringRef > , Reference < TCMachineInfo > > machine_info ; / / all machines info . Key must be unique across processes on the same machine <nl> + std : : map < Standalone < StringRef > , Reference < TCMachineInfo > > machine_info ; / / All machines info . Key must be unique across processes on the same machine <nl> std : : vector < Reference < TCMachineTeamInfo > > machineTeams ; / / all machine teams <nl> LocalityMap < UID > machineLocalityMap ; / / locality info of machines <nl> <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> / / tracking is " edge triggered " ) <nl> / / SOMEDAY : Account for capacity , load ( when shardMetrics load is high ) <nl> <nl> - ASSERT ( self - > teams . size ( ) ) ; <nl> + / / self - > teams . size ( ) can be 0 under the test - f foundationdb / tests / slow / ConfigureTest . txt - b on - s 780181629 <nl> + / / The situation happens rarely . We may want to eliminate this situation someday <nl> + if ( ! self - > teams . size ( ) ) { <nl> + req . reply . send ( Optional < Reference < IDataDistributionTeam > > ( ) ) ; <nl> + return Void ( ) ; <nl> + } <nl> <nl> int64_t bestLoadBytes = 0 ; <nl> Optional < Reference < IDataDistributionTeam > > bestOption ; <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> / / A non - initial team must have its machine team created and its size must be correct <nl> ASSERT ( isInitialTeam | | <nl> ( machineTeamInfo . isValid ( ) & & teamInfo - > serverIDs . size ( ) = = configuration . storageTeamSize ) ) ; <nl> + <nl> / / Create a machine team if it does not exist <nl> / / Note an initial team may be added at init ( ) even though the team size is not storageTeamSize <nl> if ( ! machineTeamInfo . isValid ( ) & & ! machineIDs . empty ( ) ) { <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> } <nl> } <nl> <nl> - void traceAllInfo ( bool shouldPrint ) { <nl> + / / To enable verbose debug info , set shouldPrint to true <nl> + void traceAllInfo ( bool shouldPrint = false ) { <nl> if ( ! shouldPrint ) <nl> return ; <nl> <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> traceMachineLocalityMap ( ) ; <nl> } <nl> <nl> - void traceAllInfo ( ) { <nl> - traceAllInfo ( false ) ; / / set to true to enable verbose debug info <nl> - } <nl> - <nl> + / / We must rebuild machine locality map whenever the entry in the map is inserted or removed <nl> void rebuildMachineLocalityMap ( ) { <nl> machineLocalityMap . clear ( ) ; <nl> int numHealthyMachine = 0 ; <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> } <nl> } <nl> <nl> - <nl> - / * <nl> - * Create machineTeamsToBuild number of machine teams <nl> - * No operation if machineTeamsToBuild is 0 <nl> - * <nl> - * Five steps to create each machine team , which are document in the function <nl> - * Reuse ReplicationPolicy selectReplicas func to select machine team <nl> - * return number of added machine teams <nl> - * / <nl> + / / Create machineTeamsToBuild number of machine teams <nl> + / / No operation if machineTeamsToBuild is 0 <nl> + / / <nl> + / / Five steps to create each machine team , which are document in the function <nl> + / / Reuse ReplicationPolicy selectReplicas func to select machine team <nl> + / / return number of added machine teams <nl> int addBestMachineTeams ( int targetMachineTeamsToBuild ) { <nl> int addedMachineTeams = 0 ; <nl> int totalServerIndex = 0 ; <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> machineTeamsToBuild = targetMachineTeamsToBuild ; <nl> <nl> if ( machine_info . size ( ) < configuration . storageTeamSize ) { <nl> - TraceEvent ( SevWarn , " DataDistributionBuildMachineTeams " , masterId ) <nl> + TraceEvent ( SevWarn , " DataDistributionBuildMachineTeams " , masterId ) . suppressFor ( 10 ) <nl> . detail ( " Reason " , " Not enough machines for a team . Machine number should be larger than Team size " ) <nl> . detail ( " MachineNumber " , machine_info . size ( ) ) . detail ( " TeamSize " , configuration . storageTeamSize ) ; <nl> return addedMachineTeams ; <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> std : : vector < UID * > bestTeam ; <nl> int bestScore = std : : numeric_limits < int > : : max ( ) ; <nl> int maxAttempts = SERVER_KNOBS - > BEST_OF_AMT ; / / BEST_OF_AMT = 4 <nl> - for ( int i = 0 ; i < maxAttempts & & i < 100 ; i + + ) { <nl> + for ( int i = 0 ; i < maxAttempts & & i < 100 ; i + + ) { <nl> / / Choose a team that balances the # of teams per server among the teams that have the least - utilized server <nl> team . clear ( ) ; <nl> auto success = machineLocalityMap . selectReplicas ( configuration . storagePolicy , forcedAttributes , team ) ; <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> / / selectReplicas ( ) may return server not in server_info . Retry if it happens <nl> / / Reproduce the situation with - r simulation - f foundationdb / tests / fast / BackupToDBCorrectnessClean . txt - b on - s 801184616 <nl> / / MX : Q : Why should selectReplicas return invalid server . Should not we avoid this in selectReplicas . <nl> + / / TODO : Test it by triggering SevError . If no SevError is triggered , change it to assert <nl> int valid = true ; <nl> for ( auto & pUID : team ) { <nl> if ( server_info . find ( * pUID ) = = server_info . end ( ) ) { <nl> - TraceEvent ( " SelectReplicasChoseInvalidTeam " ) . detail ( " Primary " , primary ) <nl> + TraceEvent ( SevError , " SelectReplicasChoseInvalidTeam " ) . detail ( " Primary " , primary ) <nl> . detail ( " AddedMachineTeams " , addedMachineTeams ) <nl> . detail ( " Attempt " , i ) . detail ( " ServerInfoSize " , server_info . size ( ) ) <nl> . detail ( " InvalidUID " , ( * pUID ) . toString ( ) ) <nl> . detail ( " ServerTeamNum " , server_info [ * pUID ] - > teams . size ( ) ) <nl> . detail ( " DesiredTeamsPerServer " , SERVER_KNOBS - > DESIRED_TEAMS_PER_SERVER ) ; <nl> - traceAllInfo ( ) ; <nl> + traceAllInfo ( true ) ; <nl> valid = false ; <nl> break ; <nl> } <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> } <nl> <nl> / / MX : Q : why will this happen ? If this happens , it means selectReplicas ( ) did not choose a correct team in the first place ! <nl> + / / TODO : Test it by triggering SevError . If no SevError is triggered , change it to assert <nl> if ( team . size ( ) ! = configuration . storageTeamSize ) { <nl> + TraceEvent ( SevError , " SelectReplicasChooseATeamWithIncorrectSize " ) ; <nl> + traceAllInfo ( true ) ; <nl> maxAttempts + = 1 ; <nl> } <nl> <nl>
TeamCollection : Fix a bug introduced in code review
apple/foundationdb
52c6a666011e464e24283681990c782fb98b4ca2
2018-11-17T00:34:38Z
mmm a / SConstruct <nl> ppp b / SConstruct <nl> platform_exporters = [ ] <nl> platform_apis = [ ] <nl> global_defaults = [ ] <nl> <nl> - for x in glob . glob ( " platform / * " ) : <nl> + for x in sorted ( glob . glob ( " platform / * " ) ) : <nl> if ( not os . path . isdir ( x ) or not os . path . exists ( x + " / detect . py " ) ) : <nl> continue <nl> tmppath = " . / " + x <nl> mmm a / editor / SCsub <nl> ppp b / editor / SCsub <nl> if env [ ' tools ' ] : <nl> # Fonts <nl> flist = glob . glob ( path + " / . . / thirdparty / fonts / * . ttf " ) <nl> flist . extend ( glob . glob ( path + " / . . / thirdparty / fonts / * . otf " ) ) <nl> + flist . sort ( ) <nl> env . Depends ( ' # editor / builtin_fonts . gen . h ' , flist ) <nl> env . CommandNoCache ( ' # editor / builtin_fonts . gen . h ' , flist , run_in_subprocess ( editor_builders . make_fonts_header ) ) <nl> <nl> mmm a / methods . py <nl> ppp b / methods . py <nl> def add_source_files ( self , sources , filetype , lib_env = None , shared = False ) : <nl> <nl> if isbasestring ( filetype ) : <nl> dir_path = self . Dir ( ' . ' ) . abspath <nl> - filetype = glob . glob ( dir_path + " / " + filetype ) <nl> + filetype = sorted ( glob . glob ( dir_path + " / " + filetype ) ) <nl> <nl> for path in filetype : <nl> sources . append ( self . Object ( path ) ) <nl>
BuildSystem : Sort input file lists
godotengine/godot
83b856c0465c40ecd9768508f31d3e337e1a64e1
2018-08-29T08:24:07Z
mmm a / tests / performance / decimal_casts . xml <nl> ppp b / tests / performance / decimal_casts . xml <nl> <nl> - < test > <nl> + < test max_ignored_relative_change = " 0 . 15 " > <nl> < settings > <nl> < max_memory_usage > 10G < / max_memory_usage > <nl> < / settings > <nl> <nl> < create_query > CREATE TABLE t ( x UInt64 , d32 Decimal32 ( 3 ) , d64 Decimal64 ( 4 ) , d128 Decimal128 ( 5 ) ) ENGINE = Memory < / create_query > <nl> < ! - - use less threads to save memory - - > <nl> - < fill_query > INSERT INTO t SELECT number AS x , x % 1000000 AS d32 , x AS d64 , x d128 FROM numbers_mt ( 50000000 ) SETTINGS max_threads = 8 < / fill_query > <nl> + < fill_query > INSERT INTO t SELECT number AS x , x % 1000000 AS d32 , x AS d64 , x d128 FROM numbers_mt ( 25000000 ) SETTINGS max_threads = 8 < / fill_query > <nl> < drop_query > DROP TABLE IF EXISTS t < / drop_query > <nl> <nl> < query > SELECT toUInt32 ( x ) y , toDecimal32 ( y , 1 ) , toDecimal64 ( y , 5 ) , toDecimal128 ( y , 6 ) , toDecimal256 ( y , 7 ) FROM t FORMAT Null < / query > <nl>
Update decimal_casts . xml
ClickHouse/ClickHouse
13113dafdc2c9f1cdaf33814caa74d0956537fc2
2020-08-27T13:53:16Z
mmm a / util / sock . h <nl> ppp b / util / sock . h <nl> typedef int SOCKET ; <nl> # define h_errno errno <nl> inline int getLastError ( ) { return errno ; } <nl> inline void disableNagle ( int sock ) { <nl> - int x = 1 ; <nl> - if ( setsockopt ( sock , SOL_SOCKET , TCP_NODELAY , ( char * ) & x , sizeof ( x ) ) ) <nl> - cout < < " ERROR : disableNagle failed " < < endl ; <nl> + int x = 1 ; <nl> + <nl> + # ifdef SOL_TCP <nl> + int level = SOL_TCP ; <nl> + # else <nl> + int level = SOL_SOCKET ; <nl> + # endif <nl> + <nl> + if ( setsockopt ( sock , level , TCP_NODELAY , ( char * ) & x , sizeof ( x ) ) ) <nl> + { <nl> + cout < < " ERROR : disableNagle failed " < < endl ; <nl> + } <nl> } <nl> inline void prebindOptions ( int sock ) { <nl> cout < < " doing prebind option " < < endl ; <nl>
fix for nalge on linux
mongodb/mongo
67f1992ff03992235b50cb2f4ca7d226919651b2
2008-02-29T18:07:28Z
mmm a / docs / en / operations / settings / settings . md <nl> ppp b / docs / en / operations / settings / settings . md <nl> When sequential consistency is enabled , ClickHouse allows the client to execute <nl> <nl> Enables or disables : <nl> <nl> - 1 . Rewriting of queries with multiple [ JOIN clauses ] ( . . / . . / query_language / select . md # select - join ) from the short syntax to the clear syntax . <nl> + 1 . Rewriting of queries with multiple [ JOIN clauses ] ( . . / . . / query_language / select . md # select - join ) from the short syntax to the clear syntax . If the setting value is 0 , ClickHouse doesn ' t process queries with the short syntax , and throws an exception . <nl> 2 . Converting of ` CROSS JOIN ` into ` INNER JOIN ` if conditions of join allow it . <nl> <nl> Possible values : <nl> mmm a / docs / en / query_language / select . md <nl> ppp b / docs / en / query_language / select . md <nl> See the standard [ SQL JOIN ] ( https : / / en . wikipedia . org / wiki / Join_ ( SQL ) ) descriptio <nl> <nl> # # # # Multiple JOIN <nl> <nl> - ClickHouse supports multiple ` JOIN ` operations in one query . Creating a query , you can use the following types of syntax : <nl> + Performing queries , ClickHouse rewrites multiple joins into the combination of two - table joins and processes them sequentially . If there are four tables for join ClickHouse joins the first and the second , then joins the result with the third table , and at the last step , it joins the fourth one . <nl> + <nl> + If a query contains ` WHERE ` , ` PREWHERE ` , ` GROUP ` and ` ORDER BY ` clauses , ClickHouse tries to push down filters from these clauses into the intermediate join . If it cannot apply the filter to each intermediate join , ClickHouse applies the filters after all joins are completed . <nl> + <nl> + Creating a query , you can use the following types of syntax : <nl> <nl> 1 . Clear syntax . <nl> <nl>
DOCAPI - 6553 : Some clarifications .
ClickHouse/ClickHouse
de147784b906fa633d277d411e46d66d7b1168da
2019-05-21T12:17:30Z
mmm a / test / cpp / jit / test_alias_analysis . h <nl> ppp b / test / cpp / jit / test_alias_analysis . h <nl> void testAliasRegistration ( ) { <nl> } <nl> { <nl> auto registry = torch : : RegisterOperators ( ) . op ( <nl> - " aten : : rand6 ( Tensor arg1 ) - > Tensor " , <nl> + " foo : : rand6 ( Tensor arg1 ) - > Tensor " , <nl> torch : : RegisterOperators : : options ( ) <nl> . catchAllKernel ( [ ] ( at : : Tensor ) - > at : : Tensor { <nl> return at : : rand ( { 2 , 2 } ) ; <nl> } ) <nl> . aliasAnalysis ( AliasAnalysisKind : : FROM_SCHEMA ) ) ; <nl> - const auto rand_op = Symbol : : fromQualString ( " aten : : rand6 " ) ; <nl> + const auto rand_op = Symbol : : fromQualString ( " foo : : rand6 " ) ; <nl> auto graph = std : : make_shared < Graph > ( ) ; <nl> auto a = graph - > addInput ( ) ; <nl> auto b = graph - > insert ( rand_op , { a } ) ; <nl> void testAliasRegistration ( ) { <nl> } <nl> { <nl> auto registry = torch : : RegisterOperators ( ) . op ( <nl> - " aten : : rand7 ( Tensor ( a ) arg1 ) - > Tensor ( a ) " , <nl> + " foo : : rand7 ( Tensor ( a ) arg1 ) - > Tensor ( a ) " , <nl> torch : : RegisterOperators : : options ( ) <nl> . catchAllKernel ( [ ] ( at : : Tensor t ) - > at : : Tensor { return t * 2 ; } ) <nl> . aliasAnalysis ( AliasAnalysisKind : : FROM_SCHEMA ) ) ; <nl> - const auto rand_op = Symbol : : fromQualString ( " aten : : rand7 " ) ; <nl> + const auto rand_op = Symbol : : fromQualString ( " foo : : rand7 " ) ; <nl> + <nl> auto graph = std : : make_shared < Graph > ( ) ; <nl> auto a = graph - > addInput ( ) ; <nl> auto b = graph - > insert ( rand_op , { a } ) ; <nl> void testAliasRegistration ( ) { <nl> } <nl> { <nl> auto registry = torch : : RegisterOperators ( ) . op ( <nl> - " aten : : rand8 ( Tensor ( a ) arg1 ) - > Tensor ( b ) " , <nl> + " foo : : rand8 ( Tensor ( a ) arg1 ) - > Tensor ( b ) " , <nl> torch : : RegisterOperators : : options ( ) <nl> . catchAllKernel ( [ ] ( at : : Tensor t ) - > at : : Tensor { return t * 2 ; } ) <nl> . aliasAnalysis ( AliasAnalysisKind : : FROM_SCHEMA ) ) ; <nl> - const auto rand_op = Symbol : : fromQualString ( " aten : : rand8 " ) ; <nl> + const auto rand_op = Symbol : : fromQualString ( " foo : : rand8 " ) ; <nl> auto graph = std : : make_shared < Graph > ( ) ; <nl> auto a = graph - > addInput ( ) ; <nl> auto b = graph - > insert ( rand_op , { a } ) ; <nl> mmm a / torch / csrc / jit / ir . cpp <nl> ppp b / torch / csrc / jit / ir . cpp <nl> bool Node : : hasSideEffects ( ) const { <nl> " doesn ' t have one either . We don ' t know if this op has side effects . " ) ; <nl> return false ; <nl> } <nl> + <nl> if ( kind_ . is_prim ( ) | | kind_ . is_aten ( ) ) { <nl> - / / TODO This assert is only introduced to check that we don ' t break the <nl> - / / current code base . Remove this later to allow other ops to use <nl> - / / AliasAnalysisKind : : FROM_SCHEMA <nl> + / / TODO There is nothing in the system that relies on aten : : and prim : : <nl> + / / ops using AliasAnalysisKind : : FROM_SCHEMA or AliasAnalysisKind : : INTERNAL_SPECIAL_CASE , <nl> + / / but this is the intended behavior for all current ops and a good error check . <nl> + / / We can consider lifting this constraint later if we have a use case for it . <nl> TORCH_INTERNAL_ASSERT ( <nl> op - > aliasAnalysisKind ( ) = = AliasAnalysisKind : : INTERNAL_SPECIAL_CASE | | <nl> op - > aliasAnalysisKind ( ) = = AliasAnalysisKind : : FROM_SCHEMA , <nl> bool Node : : hasSideEffects ( ) const { <nl> " has " , <nl> toString ( op - > aliasAnalysisKind ( ) ) ) ; <nl> } <nl> + <nl> switch ( op - > aliasAnalysisKind ( ) ) { <nl> case AliasAnalysisKind : : PURE : <nl> return false ; <nl> mmm a / torch / csrc / jit / passes / alias_analysis . cpp <nl> ppp b / torch / csrc / jit / passes / alias_analysis . cpp <nl> void AliasDb : : analyzeImpl ( Node * node ) { <nl> " Special cases should be handled already if we ' re here . " ) ; <nl> <nl> if ( node - > kind ( ) . is_aten ( ) | | node - > kind ( ) . is_prim ( ) ) { <nl> - / / TODO This assert is only introduced to check that we don ' t break the <nl> - / / current code base . Remove this later to allow aten : : and prim : : ops to <nl> - / / use other alias analysis kinds . <nl> + / / TODO There is nothing in the system that relies on aten : : and prim : : <nl> + / / ops using AliasAnalysisKind : : FROM_SCHEMA or AliasAnalysisKind : : INTERNAL_SPECIAL_CASE , <nl> + / / but this is the intended behavior for all current ops and a good error check . <nl> + / / We can consider lifting this constraint later if we have a use case for it . <nl> TORCH_INTERNAL_ASSERT ( <nl> analysis = = AliasAnalysisKind : : FROM_SCHEMA , <nl> " aten : : and prim : : operators should use AliasAnalysisKind : : FROM_SCHEMA but " , <nl> void AliasDb : : analyzeImpl ( Node * node ) { <nl> " AliasAnalysisKind : : CONSERVATIVE / PURE / INTERNAL_SPECIAL_CASE should already have been handled above " ) ; <nl> const auto & schema = node - > schema ( ) ; <nl> <nl> - / / TODO This assert is only introduced to check that we don ' t break the <nl> - / / current code base . Remove this later to allow other ops to use <nl> - / / AliasAnalysisKind : : FROM_SCHEMA <nl> - TORCH_INTERNAL_ASSERT ( <nl> - node - > kind ( ) . is_prim ( ) | | node - > kind ( ) . is_aten ( ) , <nl> - " The current code base should only have AliasAnalysisKind : : FROM_SCHEMA for aten : : and prim : : ops but we found it for " , <nl> - node - > kind ( ) . toDisplayString ( ) , <nl> - " . We want to open this up though . " ) ; <nl> - <nl> / / Bind the schema ' s " formal " alias annotation to the actual values those <nl> / / schema arguments represent <nl> std : : unordered_map < Symbol , Value * > formalToActual ; <nl>
Open up AliasAnalysisKind for any ops ( )
pytorch/pytorch
352032c93c7697be79fd468f1a3a454c35d80852
2019-08-09T22:10:29Z
mmm a / Makefile . am <nl> ppp b / Makefile . am <nl> ruby_EXTRA_DIST = \ <nl> ruby / ext / google / protobuf_c / defs . c \ <nl> ruby / ext / google / protobuf_c / encode_decode . c \ <nl> ruby / ext / google / protobuf_c / extconf . rb \ <nl> + ruby / ext / google / protobuf_c / map . c \ <nl> ruby / ext / google / protobuf_c / message . c \ <nl> ruby / ext / google / protobuf_c / protobuf . c \ <nl> ruby / ext / google / protobuf_c / protobuf . h \ <nl> ruby_EXTRA_DIST = \ <nl> ruby / google - protobuf . gemspec \ <nl> ruby / lib / google / protobuf . rb \ <nl> ruby / tests / basic . rb \ <nl> - ruby / tests / stress . rb <nl> + ruby / tests / stress . rb \ <nl> + ruby / tests / generated_code . proto \ <nl> + ruby / tests / generated_code . rb \ <nl> + ruby / tests / generated_code_test . rb <nl> <nl> all_EXTRA_DIST = $ ( java_EXTRA_DIST ) $ ( python_EXTRA_DIST ) $ ( ruby_EXTRA_DIST ) <nl> <nl> mmm a / ruby / ext / google / protobuf_c / defs . c <nl> ppp b / ruby / ext / google / protobuf_c / defs . c <nl> static upb_def * check_notfrozen ( const upb_def * def ) { <nl> } <nl> <nl> static upb_msgdef * check_msg_notfrozen ( const upb_msgdef * def ) { <nl> - return ( upb_msgdef * ) check_notfrozen ( ( const upb_def * ) def ) ; <nl> + return upb_downcast_msgdef_mutable ( check_notfrozen ( ( const upb_def * ) def ) ) ; <nl> } <nl> <nl> static upb_fielddef * check_field_notfrozen ( const upb_fielddef * def ) { <nl> - return ( upb_fielddef * ) check_notfrozen ( ( const upb_def * ) def ) ; <nl> + return upb_downcast_fielddef_mutable ( check_notfrozen ( ( const upb_def * ) def ) ) ; <nl> + } <nl> + <nl> + static upb_oneofdef * check_oneof_notfrozen ( const upb_oneofdef * def ) { <nl> + return ( upb_oneofdef * ) check_notfrozen ( ( const upb_def * ) def ) ; <nl> } <nl> <nl> static upb_enumdef * check_enum_notfrozen ( const upb_enumdef * def ) { <nl> void Descriptor_register ( VALUE module ) { <nl> rb_define_method ( klass , " each " , Descriptor_each , 0 ) ; <nl> rb_define_method ( klass , " lookup " , Descriptor_lookup , 1 ) ; <nl> rb_define_method ( klass , " add_field " , Descriptor_add_field , 1 ) ; <nl> + rb_define_method ( klass , " add_oneof " , Descriptor_add_oneof , 1 ) ; <nl> + rb_define_method ( klass , " each_oneof " , Descriptor_each_oneof , 0 ) ; <nl> + rb_define_method ( klass , " lookup_oneof " , Descriptor_lookup_oneof , 1 ) ; <nl> rb_define_method ( klass , " msgclass " , Descriptor_msgclass , 0 ) ; <nl> rb_define_method ( klass , " name " , Descriptor_name , 0 ) ; <nl> rb_define_method ( klass , " name = " , Descriptor_name_set , 1 ) ; <nl> VALUE Descriptor_name_set ( VALUE _self , VALUE str ) { <nl> VALUE Descriptor_each ( VALUE _self ) { <nl> DEFINE_SELF ( Descriptor , self , _self ) ; <nl> <nl> - upb_msg_iter it ; <nl> - for ( upb_msg_begin ( & it , self - > msgdef ) ; <nl> - ! upb_msg_done ( & it ) ; <nl> - upb_msg_next ( & it ) ) { <nl> + upb_msg_field_iter it ; <nl> + for ( upb_msg_field_begin ( & it , self - > msgdef ) ; <nl> + ! upb_msg_field_done ( & it ) ; <nl> + upb_msg_field_next ( & it ) ) { <nl> const upb_fielddef * field = upb_msg_iter_field ( & it ) ; <nl> VALUE obj = get_def_obj ( field ) ; <nl> rb_yield ( obj ) ; <nl> VALUE Descriptor_lookup ( VALUE _self , VALUE name ) { <nl> * call - seq : <nl> * Descriptor . add_field ( field ) = > nil <nl> * <nl> - * Adds the given FieldDescriptor to this message type . The descriptor must not <nl> + * Adds the given FieldDescriptor to this message type . This descriptor must not <nl> * have been added to a pool yet . Raises an exception if a field with the same <nl> * name or number already exists . Sub - type references ( e . g . for fields of type <nl> * message ) are not resolved at this point . <nl> VALUE Descriptor_add_field ( VALUE _self , VALUE obj ) { <nl> return Qnil ; <nl> } <nl> <nl> + / * <nl> + * call - seq : <nl> + * Descriptor . add_oneof ( oneof ) = > nil <nl> + * <nl> + * Adds the given OneofDescriptor to this message type . This descriptor must not <nl> + * have been added to a pool yet . Raises an exception if a oneof with the same <nl> + * name already exists , or if any of the oneof ' s fields ' names or numbers <nl> + * conflict with an existing field in this message type . All fields in the oneof <nl> + * are added to the message descriptor . Sub - type references ( e . g . for fields of <nl> + * type message ) are not resolved at this point . <nl> + * / <nl> + VALUE Descriptor_add_oneof ( VALUE _self , VALUE obj ) { <nl> + DEFINE_SELF ( Descriptor , self , _self ) ; <nl> + upb_msgdef * mut_def = check_msg_notfrozen ( self - > msgdef ) ; <nl> + OneofDescriptor * def = ruby_to_OneofDescriptor ( obj ) ; <nl> + upb_oneofdef * mut_oneof_def = check_oneof_notfrozen ( def - > oneofdef ) ; <nl> + CHECK_UPB ( <nl> + upb_msgdef_addoneof ( mut_def , mut_oneof_def , NULL , & status ) , <nl> + " Adding oneof to Descriptor failed " ) ; <nl> + add_def_obj ( def - > oneofdef , obj ) ; <nl> + return Qnil ; <nl> + } <nl> + <nl> + / * <nl> + * call - seq : <nl> + * Descriptor . each_oneof ( & block ) = > nil <nl> + * <nl> + * Invokes the given block for each oneof in this message type , passing the <nl> + * corresponding OneofDescriptor . <nl> + * / <nl> + VALUE Descriptor_each_oneof ( VALUE _self ) { <nl> + DEFINE_SELF ( Descriptor , self , _self ) ; <nl> + <nl> + upb_msg_oneof_iter it ; <nl> + for ( upb_msg_oneof_begin ( & it , self - > msgdef ) ; <nl> + ! upb_msg_oneof_done ( & it ) ; <nl> + upb_msg_oneof_next ( & it ) ) { <nl> + const upb_oneofdef * oneof = upb_msg_iter_oneof ( & it ) ; <nl> + VALUE obj = get_def_obj ( oneof ) ; <nl> + rb_yield ( obj ) ; <nl> + } <nl> + return Qnil ; <nl> + } <nl> + <nl> + / * <nl> + * call - seq : <nl> + * Descriptor . lookup_oneof ( name ) = > OneofDescriptor <nl> + * <nl> + * Returns the oneof descriptor for the oneof with the given name , if present , <nl> + * or nil if none . <nl> + * / <nl> + VALUE Descriptor_lookup_oneof ( VALUE _self , VALUE name ) { <nl> + DEFINE_SELF ( Descriptor , self , _self ) ; <nl> + const char * s = get_str ( name ) ; <nl> + const upb_oneofdef * oneof = upb_msgdef_ntooz ( self - > msgdef , s ) ; <nl> + if ( oneof = = NULL ) { <nl> + return Qnil ; <nl> + } <nl> + return get_def_obj ( oneof ) ; <nl> + } <nl> + <nl> / * <nl> * call - seq : <nl> * Descriptor . msgclass = > message_klass <nl> VALUE FieldDescriptor_set ( VALUE _self , VALUE msg_rb , VALUE value ) { <nl> return Qnil ; <nl> } <nl> <nl> + / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> + / / OneofDescriptor . <nl> + / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> + <nl> + DEFINE_CLASS ( OneofDescriptor , " Google : : Protobuf : : OneofDescriptor " ) ; <nl> + <nl> + void OneofDescriptor_mark ( void * _self ) { <nl> + } <nl> + <nl> + void OneofDescriptor_free ( void * _self ) { <nl> + OneofDescriptor * self = _self ; <nl> + upb_oneofdef_unref ( self - > oneofdef , & self - > oneofdef ) ; <nl> + xfree ( self ) ; <nl> + } <nl> + <nl> + / * <nl> + * call - seq : <nl> + * OneofDescriptor . new = > oneof_descriptor <nl> + * <nl> + * Creates a new , empty , oneof descriptor . The oneof may only be modified prior <nl> + * to being added to a message descriptor which is subsequently added to a pool . <nl> + * / <nl> + VALUE OneofDescriptor_alloc ( VALUE klass ) { <nl> + OneofDescriptor * self = ALLOC ( OneofDescriptor ) ; <nl> + VALUE ret = TypedData_Wrap_Struct ( klass , & _OneofDescriptor_type , self ) ; <nl> + self - > oneofdef = upb_oneofdef_new ( & self - > oneofdef ) ; <nl> + return ret ; <nl> + } <nl> + <nl> + void OneofDescriptor_register ( VALUE module ) { <nl> + VALUE klass = rb_define_class_under ( <nl> + module , " OneofDescriptor " , rb_cObject ) ; <nl> + rb_define_alloc_func ( klass , OneofDescriptor_alloc ) ; <nl> + rb_define_method ( klass , " name " , OneofDescriptor_name , 0 ) ; <nl> + rb_define_method ( klass , " name = " , OneofDescriptor_name_set , 1 ) ; <nl> + rb_define_method ( klass , " add_field " , OneofDescriptor_add_field , 1 ) ; <nl> + rb_define_method ( klass , " each " , OneofDescriptor_each , 0 ) ; <nl> + rb_include_module ( klass , rb_mEnumerable ) ; <nl> + cOneofDescriptor = klass ; <nl> + rb_gc_register_address ( & cOneofDescriptor ) ; <nl> + } <nl> + <nl> + / * <nl> + * call - seq : <nl> + * OneofDescriptor . name = > name <nl> + * <nl> + * Returns the name of this oneof . <nl> + * / <nl> + VALUE OneofDescriptor_name ( VALUE _self ) { <nl> + DEFINE_SELF ( OneofDescriptor , self , _self ) ; <nl> + return rb_str_maybe_null ( upb_oneofdef_name ( self - > oneofdef ) ) ; <nl> + } <nl> + <nl> + / * <nl> + * call - seq : <nl> + * OneofDescriptor . name = name <nl> + * <nl> + * Sets a new name for this oneof . The oneof must not have been added to a <nl> + * message descriptor yet . <nl> + * / <nl> + VALUE OneofDescriptor_name_set ( VALUE _self , VALUE value ) { <nl> + DEFINE_SELF ( OneofDescriptor , self , _self ) ; <nl> + upb_oneofdef * mut_def = check_oneof_notfrozen ( self - > oneofdef ) ; <nl> + const char * str = get_str ( value ) ; <nl> + CHECK_UPB ( upb_oneofdef_setname ( mut_def , str , & status ) , <nl> + " Error setting oneof name " ) ; <nl> + return Qnil ; <nl> + } <nl> + <nl> + / * <nl> + * call - seq : <nl> + * OneofDescriptor . add_field ( field ) = > nil <nl> + * <nl> + * Adds a field to this oneof . The field may have been added to this oneof in <nl> + * the past , or the message to which this oneof belongs ( if any ) , but may not <nl> + * have already been added to any other oneof or message . Otherwise , an <nl> + * exception is raised . <nl> + * <nl> + * All fields added to the oneof via this method will be automatically added to <nl> + * the message to which this oneof belongs , if it belongs to one currently , or <nl> + * else will be added to any message to which the oneof is later added at the <nl> + * time that it is added . <nl> + * / <nl> + VALUE OneofDescriptor_add_field ( VALUE _self , VALUE obj ) { <nl> + DEFINE_SELF ( OneofDescriptor , self , _self ) ; <nl> + upb_oneofdef * mut_def = check_oneof_notfrozen ( self - > oneofdef ) ; <nl> + FieldDescriptor * def = ruby_to_FieldDescriptor ( obj ) ; <nl> + upb_fielddef * mut_field_def = check_field_notfrozen ( def - > fielddef ) ; <nl> + CHECK_UPB ( <nl> + upb_oneofdef_addfield ( mut_def , mut_field_def , NULL , & status ) , <nl> + " Adding field to OneofDescriptor failed " ) ; <nl> + add_def_obj ( def - > fielddef , obj ) ; <nl> + return Qnil ; <nl> + } <nl> + <nl> + / * <nl> + * call - seq : <nl> + * OneofDescriptor . each ( & block ) = > nil <nl> + * <nl> + * Iterates through fields in this oneof , yielding to the block on each one . <nl> + * / <nl> + VALUE OneofDescriptor_each ( VALUE _self , VALUE field ) { <nl> + DEFINE_SELF ( OneofDescriptor , self , _self ) ; <nl> + upb_oneof_iter it ; <nl> + for ( upb_oneof_begin ( & it , self - > oneofdef ) ; <nl> + ! upb_oneof_done ( & it ) ; <nl> + upb_oneof_next ( & it ) ) { <nl> + const upb_fielddef * f = upb_oneof_iter_field ( & it ) ; <nl> + VALUE obj = get_def_obj ( f ) ; <nl> + rb_yield ( obj ) ; <nl> + } <nl> + return Qnil ; <nl> + } <nl> + <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> / / EnumDescriptor . <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> void MessageBuilderContext_register ( VALUE module ) { <nl> rb_define_method ( klass , " required " , MessageBuilderContext_required , - 1 ) ; <nl> rb_define_method ( klass , " repeated " , MessageBuilderContext_repeated , - 1 ) ; <nl> rb_define_method ( klass , " map " , MessageBuilderContext_map , - 1 ) ; <nl> + rb_define_method ( klass , " oneof " , MessageBuilderContext_oneof , 1 ) ; <nl> cMessageBuilderContext = klass ; <nl> rb_gc_register_address ( & cMessageBuilderContext ) ; <nl> } <nl> VALUE MessageBuilderContext_map ( int argc , VALUE * argv , VALUE _self ) { <nl> return Qnil ; <nl> } <nl> <nl> + / * <nl> + * call - seq : <nl> + * MessageBuilderContext . oneof ( name , & block ) = > nil <nl> + * <nl> + * Creates a new OneofDescriptor with the given name , creates a <nl> + * OneofBuilderContext attached to that OneofDescriptor , evaluates the given <nl> + * block in the context of that OneofBuilderContext with # instance_eval , and <nl> + * then adds the oneof to the message . <nl> + * <nl> + * This is the recommended , idiomatic way to build oneof definitions . <nl> + * / <nl> + VALUE MessageBuilderContext_oneof ( VALUE _self , VALUE name ) { <nl> + DEFINE_SELF ( MessageBuilderContext , self , _self ) ; <nl> + VALUE oneofdef = rb_class_new_instance ( 0 , NULL , cOneofDescriptor ) ; <nl> + VALUE args [ 2 ] = { oneofdef , self - > builder } ; <nl> + VALUE ctx = rb_class_new_instance ( 2 , args , cOneofBuilderContext ) ; <nl> + VALUE block = rb_block_proc ( ) ; <nl> + VALUE name_str = rb_str_new2 ( rb_id2name ( SYM2ID ( name ) ) ) ; <nl> + rb_funcall ( oneofdef , rb_intern ( " name = " ) , 1 , name_str ) ; <nl> + rb_funcall_with_block ( ctx , rb_intern ( " instance_eval " ) , 0 , NULL , block ) ; <nl> + Descriptor_add_oneof ( self - > descriptor , oneofdef ) ; <nl> + <nl> + return Qnil ; <nl> + } <nl> + <nl> + / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> + / / OneofBuilderContext . <nl> + / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> + <nl> + DEFINE_CLASS ( OneofBuilderContext , <nl> + " Google : : Protobuf : : Internal : : OneofBuilderContext " ) ; <nl> + <nl> + void OneofBuilderContext_mark ( void * _self ) { <nl> + OneofBuilderContext * self = _self ; <nl> + rb_gc_mark ( self - > descriptor ) ; <nl> + rb_gc_mark ( self - > builder ) ; <nl> + } <nl> + <nl> + void OneofBuilderContext_free ( void * _self ) { <nl> + OneofBuilderContext * self = _self ; <nl> + xfree ( self ) ; <nl> + } <nl> + <nl> + VALUE OneofBuilderContext_alloc ( VALUE klass ) { <nl> + OneofBuilderContext * self = ALLOC ( OneofBuilderContext ) ; <nl> + VALUE ret = TypedData_Wrap_Struct ( <nl> + klass , & _OneofBuilderContext_type , self ) ; <nl> + self - > descriptor = Qnil ; <nl> + self - > builder = Qnil ; <nl> + return ret ; <nl> + } <nl> + <nl> + void OneofBuilderContext_register ( VALUE module ) { <nl> + VALUE klass = rb_define_class_under ( <nl> + module , " OneofBuilderContext " , rb_cObject ) ; <nl> + rb_define_alloc_func ( klass , OneofBuilderContext_alloc ) ; <nl> + rb_define_method ( klass , " initialize " , <nl> + OneofBuilderContext_initialize , 2 ) ; <nl> + rb_define_method ( klass , " optional " , OneofBuilderContext_optional , - 1 ) ; <nl> + cOneofBuilderContext = klass ; <nl> + rb_gc_register_address ( & cOneofBuilderContext ) ; <nl> + } <nl> + <nl> + / * <nl> + * call - seq : <nl> + * OneofBuilderContext . new ( desc , builder ) = > context <nl> + * <nl> + * Create a new oneof builder context around the given oneof descriptor and <nl> + * builder context . This class is intended to serve as a DSL context to be used <nl> + * with # instance_eval . <nl> + * / <nl> + VALUE OneofBuilderContext_initialize ( VALUE _self , <nl> + VALUE oneofdef , <nl> + VALUE builder ) { <nl> + DEFINE_SELF ( OneofBuilderContext , self , _self ) ; <nl> + self - > descriptor = oneofdef ; <nl> + self - > builder = builder ; <nl> + return Qnil ; <nl> + } <nl> + <nl> + / * <nl> + * call - seq : <nl> + * OneofBuilderContext . optional ( name , type , number , type_class = nil ) <nl> + * <nl> + * Defines a new optional field in this oneof with the given type , tag number , <nl> + * and type class ( for message and enum fields ) . The type must be a Ruby symbol <nl> + * ( as accepted by FieldDescriptor # type = ) and the type_class must be a string , <nl> + * if present ( as accepted by FieldDescriptor # submsg_name = ) . <nl> + * / <nl> + VALUE OneofBuilderContext_optional ( int argc , VALUE * argv , VALUE _self ) { <nl> + DEFINE_SELF ( OneofBuilderContext , self , _self ) ; <nl> + <nl> + if ( argc < 3 ) { <nl> + rb_raise ( rb_eArgError , " Expected at least 3 arguments . " ) ; <nl> + } <nl> + VALUE name = argv [ 0 ] ; <nl> + VALUE type = argv [ 1 ] ; <nl> + VALUE number = argv [ 2 ] ; <nl> + VALUE type_class = ( argc > 3 ) ? argv [ 3 ] : Qnil ; <nl> + <nl> + return msgdef_add_field ( self - > descriptor , " optional " , <nl> + name , type , number , type_class ) ; <nl> + } <nl> + <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> / / EnumBuilderContext . <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> VALUE Builder_add_enum ( VALUE _self , VALUE name ) { <nl> <nl> static void validate_msgdef ( const upb_msgdef * msgdef ) { <nl> / / Verify that no required fields exist . proto3 does not support these . <nl> - upb_msg_iter it ; <nl> - for ( upb_msg_begin ( & it , msgdef ) ; ! upb_msg_done ( & it ) ; upb_msg_next ( & it ) ) { <nl> + upb_msg_field_iter it ; <nl> + for ( upb_msg_field_begin ( & it , msgdef ) ; <nl> + ! upb_msg_field_done ( & it ) ; <nl> + upb_msg_field_next ( & it ) ) { <nl> const upb_fielddef * field = upb_msg_iter_field ( & it ) ; <nl> if ( upb_fielddef_label ( field ) = = UPB_LABEL_REQUIRED ) { <nl> rb_raise ( rb_eTypeError , " Required fields are unsupported in proto3 . " ) ; <nl> mmm a / ruby / ext / google / protobuf_c / encode_decode . c <nl> ppp b / ruby / ext / google / protobuf_c / encode_decode . c <nl> static const void * newsubmsghandlerdata ( upb_handlers * h , uint32_t ofs , <nl> return hd ; <nl> } <nl> <nl> + typedef struct { <nl> + size_t ofs ; / / union data slot <nl> + size_t case_ofs ; / / oneof_case field <nl> + uint32_t oneof_case_num ; / / oneof - case number to place in oneof_case field <nl> + const upb_msgdef * md ; / / msgdef , for oneof submessage handler <nl> + } oneof_handlerdata_t ; <nl> + <nl> + static const void * newoneofhandlerdata ( upb_handlers * h , <nl> + uint32_t ofs , <nl> + uint32_t case_ofs , <nl> + const upb_fielddef * f ) { <nl> + oneof_handlerdata_t * hd = ALLOC ( oneof_handlerdata_t ) ; <nl> + hd - > ofs = ofs ; <nl> + hd - > case_ofs = case_ofs ; <nl> + / / We reuse the field tag number as a oneof union discriminant tag . Note that <nl> + / / we don ' t expose these numbers to the user , so the only requirement is that <nl> + / / we have some unique ID for each union case / possibility . The field tag <nl> + / / numbers are already present and are easy to use so there ' s no reason to <nl> + / / create a separate ID space . In addition , using the field tag number here <nl> + / / lets us easily look up the field in the oneof accessor . <nl> + hd - > oneof_case_num = upb_fielddef_number ( f ) ; <nl> + if ( upb_fielddef_type ( f ) = = UPB_TYPE_MESSAGE ) { <nl> + hd - > md = upb_fielddef_msgsubdef ( f ) ; <nl> + } else { <nl> + hd - > md = NULL ; <nl> + } <nl> + upb_handlers_addcleanup ( h , hd , free ) ; <nl> + return hd ; <nl> + } <nl> + <nl> / / A handler that starts a repeated field . Gets the Repeated * Field instance for <nl> / / this field ( such an instance always exists even in an empty message ) . <nl> static void * startseq_handler ( void * closure , const void * hd ) { <nl> static void * startseq_handler ( void * closure , const void * hd ) { <nl> return ( void * ) DEREF ( msg , * ofs , VALUE ) ; <nl> } <nl> <nl> - / / Handlers that append primitive values to a repeated field ( a regular Ruby <nl> - / / array for now ) . <nl> + / / Handlers that append primitive values to a repeated field . <nl> # define DEFINE_APPEND_HANDLER ( type , ctype ) \ <nl> static bool append # # type # # _handler ( void * closure , const void * hd , \ <nl> ctype val ) { \ <nl> DEFINE_APPEND_HANDLER ( int64 , int64_t ) <nl> DEFINE_APPEND_HANDLER ( uint64 , uint64_t ) <nl> DEFINE_APPEND_HANDLER ( double , double ) <nl> <nl> - / / Appends a string to a repeated field ( a regular Ruby array for now ) . <nl> + / / Appends a string to a repeated field . <nl> static void * appendstr_handler ( void * closure , <nl> const void * hd , <nl> size_t size_hint ) { <nl> static void * appendstr_handler ( void * closure , <nl> return ( void * ) str ; <nl> } <nl> <nl> - / / Appends a ' bytes ' string to a repeated field ( a regular Ruby array for now ) . <nl> + / / Appends a ' bytes ' string to a repeated field . <nl> static void * appendbytes_handler ( void * closure , <nl> const void * hd , <nl> size_t size_hint ) { <nl> static map_handlerdata_t * new_map_handlerdata ( <nl> return hd ; <nl> } <nl> <nl> + / / Handlers that set primitive values in oneofs . <nl> + # define DEFINE_ONEOF_HANDLER ( type , ctype ) \ <nl> + static bool oneof # # type # # _handler ( void * closure , const void * hd , \ <nl> + ctype val ) { \ <nl> + const oneof_handlerdata_t * oneofdata = hd ; \ <nl> + DEREF ( closure , oneofdata - > case_ofs , uint32_t ) = \ <nl> + oneofdata - > oneof_case_num ; \ <nl> + DEREF ( closure , oneofdata - > ofs , ctype ) = val ; \ <nl> + return true ; \ <nl> + } <nl> + <nl> + DEFINE_ONEOF_HANDLER ( bool , bool ) <nl> + DEFINE_ONEOF_HANDLER ( int32 , int32_t ) <nl> + DEFINE_ONEOF_HANDLER ( uint32 , uint32_t ) <nl> + DEFINE_ONEOF_HANDLER ( float , float ) <nl> + DEFINE_ONEOF_HANDLER ( int64 , int64_t ) <nl> + DEFINE_ONEOF_HANDLER ( uint64 , uint64_t ) <nl> + DEFINE_ONEOF_HANDLER ( double , double ) <nl> + <nl> + # undef DEFINE_ONEOF_HANDLER <nl> + <nl> + / / Handlers for strings in a oneof . <nl> + static void * oneofstr_handler ( void * closure , <nl> + const void * hd , <nl> + size_t size_hint ) { <nl> + MessageHeader * msg = closure ; <nl> + const oneof_handlerdata_t * oneofdata = hd ; <nl> + VALUE str = rb_str_new2 ( " " ) ; <nl> + rb_enc_associate ( str , kRubyStringUtf8Encoding ) ; <nl> + DEREF ( msg , oneofdata - > case_ofs , uint32_t ) = <nl> + oneofdata - > oneof_case_num ; <nl> + DEREF ( msg , oneofdata - > ofs , VALUE ) = str ; <nl> + return ( void * ) str ; <nl> + } <nl> + <nl> + static void * oneofbytes_handler ( void * closure , <nl> + const void * hd , <nl> + size_t size_hint ) { <nl> + MessageHeader * msg = closure ; <nl> + const oneof_handlerdata_t * oneofdata = hd ; <nl> + VALUE str = rb_str_new2 ( " " ) ; <nl> + rb_enc_associate ( str , kRubyString8bitEncoding ) ; <nl> + DEREF ( msg , oneofdata - > case_ofs , uint32_t ) = <nl> + oneofdata - > oneof_case_num ; <nl> + DEREF ( msg , oneofdata - > ofs , VALUE ) = str ; <nl> + return ( void * ) str ; <nl> + } <nl> + <nl> + / / Handler for a submessage field in a oneof . <nl> + static void * oneofsubmsg_handler ( void * closure , <nl> + const void * hd ) { <nl> + MessageHeader * msg = closure ; <nl> + const oneof_handlerdata_t * oneofdata = hd ; <nl> + uint32_t oldcase = DEREF ( msg , oneofdata - > case_ofs , uint32_t ) ; <nl> + <nl> + VALUE subdesc = <nl> + get_def_obj ( ( void * ) oneofdata - > md ) ; <nl> + VALUE subklass = Descriptor_msgclass ( subdesc ) ; <nl> + <nl> + if ( oldcase ! = oneofdata - > oneof_case_num | | <nl> + DEREF ( msg , oneofdata - > ofs , VALUE ) = = Qnil ) { <nl> + DEREF ( msg , oneofdata - > ofs , VALUE ) = <nl> + rb_class_new_instance ( 0 , NULL , subklass ) ; <nl> + } <nl> + / / Set the oneof case * after * allocating the new class instance - - otherwise , <nl> + / / if the Ruby GC is invoked as part of a call into the VM , it might invoke <nl> + / / our mark routines , and our mark routines might see the case value <nl> + / / indicating a VALUE is present and expect a valid VALUE . See comment in <nl> + / / layout_set ( ) for more detail : basically , the change to the value and the <nl> + / / case must be atomic w . r . t . the Ruby VM . <nl> + DEREF ( msg , oneofdata - > case_ofs , uint32_t ) = <nl> + oneofdata - > oneof_case_num ; <nl> + <nl> + VALUE submsg_rb = DEREF ( msg , oneofdata - > ofs , VALUE ) ; <nl> + MessageHeader * submsg ; <nl> + TypedData_Get_Struct ( submsg_rb , MessageHeader , & Message_type , submsg ) ; <nl> + return submsg ; <nl> + } <nl> + <nl> / / Set up handlers for a repeated field . <nl> static void add_handlers_for_repeated_field ( upb_handlers * h , <nl> const upb_fielddef * f , <nl> static void add_handlers_for_mapentry ( const upb_msgdef * msgdef , <nl> offsetof ( map_parse_frame_t , value_storage ) ) ; <nl> } <nl> <nl> + / / Set up handlers for a oneof field . <nl> + static void add_handlers_for_oneof_field ( upb_handlers * h , <nl> + const upb_fielddef * f , <nl> + size_t offset , <nl> + size_t oneof_case_offset ) { <nl> + <nl> + upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER ; <nl> + upb_handlerattr_sethandlerdata ( <nl> + & attr , newoneofhandlerdata ( h , offset , oneof_case_offset , f ) ) ; <nl> + <nl> + switch ( upb_fielddef_type ( f ) ) { <nl> + <nl> + # define SET_HANDLER ( utype , ltype ) \ <nl> + case utype : \ <nl> + upb_handlers_set # # ltype ( h , f , oneof # # ltype # # _handler , & attr ) ; \ <nl> + break ; <nl> + <nl> + SET_HANDLER ( UPB_TYPE_BOOL , bool ) ; <nl> + SET_HANDLER ( UPB_TYPE_INT32 , int32 ) ; <nl> + SET_HANDLER ( UPB_TYPE_UINT32 , uint32 ) ; <nl> + SET_HANDLER ( UPB_TYPE_ENUM , int32 ) ; <nl> + SET_HANDLER ( UPB_TYPE_FLOAT , float ) ; <nl> + SET_HANDLER ( UPB_TYPE_INT64 , int64 ) ; <nl> + SET_HANDLER ( UPB_TYPE_UINT64 , uint64 ) ; <nl> + SET_HANDLER ( UPB_TYPE_DOUBLE , double ) ; <nl> + <nl> + # undef SET_HANDLER <nl> + <nl> + case UPB_TYPE_STRING : <nl> + case UPB_TYPE_BYTES : { <nl> + bool is_bytes = upb_fielddef_type ( f ) = = UPB_TYPE_BYTES ; <nl> + upb_handlers_setstartstr ( h , f , is_bytes ? <nl> + oneofbytes_handler : oneofstr_handler , <nl> + & attr ) ; <nl> + upb_handlers_setstring ( h , f , stringdata_handler , NULL ) ; <nl> + break ; <nl> + } <nl> + case UPB_TYPE_MESSAGE : { <nl> + upb_handlers_setstartsubmsg ( h , f , oneofsubmsg_handler , & attr ) ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + upb_handlerattr_uninit ( & attr ) ; <nl> + } <nl> + <nl> + <nl> static void add_handlers_for_message ( const void * closure , upb_handlers * h ) { <nl> const upb_msgdef * msgdef = upb_handlers_msgdef ( h ) ; <nl> Descriptor * desc = ruby_to_Descriptor ( get_def_obj ( ( void * ) msgdef ) ) ; <nl> static void add_handlers_for_message ( const void * closure , upb_handlers * h ) { <nl> desc - > layout = create_layout ( desc - > msgdef ) ; <nl> } <nl> <nl> - upb_msg_iter i ; <nl> - <nl> - for ( upb_msg_begin ( & i , desc - > msgdef ) ; <nl> - ! upb_msg_done ( & i ) ; <nl> - upb_msg_next ( & i ) ) { <nl> + upb_msg_field_iter i ; <nl> + for ( upb_msg_field_begin ( & i , desc - > msgdef ) ; <nl> + ! upb_msg_field_done ( & i ) ; <nl> + upb_msg_field_next ( & i ) ) { <nl> const upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> - size_t offset = desc - > layout - > offsets [ upb_fielddef_index ( f ) ] + <nl> + size_t offset = desc - > layout - > fields [ upb_fielddef_index ( f ) ] . offset + <nl> sizeof ( MessageHeader ) ; <nl> <nl> - if ( is_map_field ( f ) ) { <nl> + if ( upb_fielddef_containingoneof ( f ) ) { <nl> + size_t oneof_case_offset = <nl> + desc - > layout - > fields [ upb_fielddef_index ( f ) ] . case_offset + <nl> + sizeof ( MessageHeader ) ; <nl> + add_handlers_for_oneof_field ( h , f , offset , oneof_case_offset ) ; <nl> + } else if ( is_map_field ( f ) ) { <nl> add_handlers_for_mapfield ( h , f , offset , desc ) ; <nl> } else if ( upb_fielddef_isseq ( f ) ) { <nl> add_handlers_for_repeated_field ( h , f , offset ) ; <nl> static void putmsg ( VALUE msg_rb , const Descriptor * desc , <nl> MessageHeader * msg ; <nl> TypedData_Get_Struct ( msg_rb , MessageHeader , & Message_type , msg ) ; <nl> <nl> - upb_msg_iter i ; <nl> - for ( upb_msg_begin ( & i , desc - > msgdef ) ; <nl> - ! upb_msg_done ( & i ) ; <nl> - upb_msg_next ( & i ) ) { <nl> + upb_msg_field_iter i ; <nl> + for ( upb_msg_field_begin ( & i , desc - > msgdef ) ; <nl> + ! upb_msg_field_done ( & i ) ; <nl> + upb_msg_field_next ( & i ) ) { <nl> upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> uint32_t offset = <nl> - desc - > layout - > offsets [ upb_fielddef_index ( f ) ] + sizeof ( MessageHeader ) ; <nl> + desc - > layout - > fields [ upb_fielddef_index ( f ) ] . offset + <nl> + sizeof ( MessageHeader ) ; <nl> + <nl> + if ( upb_fielddef_containingoneof ( f ) ) { <nl> + uint32_t oneof_case_offset = <nl> + desc - > layout - > fields [ upb_fielddef_index ( f ) ] . case_offset + <nl> + sizeof ( MessageHeader ) ; <nl> + / / For a oneof , check that this field is actually present - - skip all the <nl> + / / below if not . <nl> + if ( DEREF ( msg , oneof_case_offset , uint32_t ) ! = <nl> + upb_fielddef_number ( f ) ) { <nl> + continue ; <nl> + } <nl> + / / Otherwise , fall through to the appropriate singular - field handler <nl> + / / below . <nl> + } <nl> <nl> if ( is_map_field ( f ) ) { <nl> VALUE map = DEREF ( msg , offset , VALUE ) ; <nl> mmm a / ruby / ext / google / protobuf_c / message . c <nl> ppp b / ruby / ext / google / protobuf_c / message . c <nl> VALUE Message_alloc ( VALUE klass ) { <nl> return ret ; <nl> } <nl> <nl> + static VALUE which_oneof_field ( MessageHeader * self , const upb_oneofdef * o ) { <nl> + / / If no fields in the oneof , always nil . <nl> + if ( upb_oneofdef_numfields ( o ) = = 0 ) { <nl> + return Qnil ; <nl> + } <nl> + / / Grab the first field in the oneof so we can get its layout info to find the <nl> + / / oneof_case field . <nl> + upb_oneof_iter it ; <nl> + upb_oneof_begin ( & it , o ) ; <nl> + assert ( ! upb_oneof_done ( & it ) ) ; <nl> + const upb_fielddef * first_field = upb_oneof_iter_field ( & it ) ; <nl> + assert ( upb_fielddef_containingoneof ( first_field ) ! = NULL ) ; <nl> + <nl> + size_t case_ofs = <nl> + self - > descriptor - > layout - > <nl> + fields [ upb_fielddef_index ( first_field ) ] . case_offset ; <nl> + uint32_t oneof_case = * ( ( uint32_t * ) ( Message_data ( self ) + case_ofs ) ) ; <nl> + <nl> + if ( oneof_case = = ONEOF_CASE_NONE ) { <nl> + return Qnil ; <nl> + } <nl> + <nl> + / / oneof_case is a field index , so find that field . <nl> + const upb_fielddef * f = upb_oneofdef_itof ( o , oneof_case ) ; <nl> + assert ( f ! = NULL ) ; <nl> + <nl> + return ID2SYM ( rb_intern ( upb_fielddef_name ( f ) ) ) ; <nl> + } <nl> + <nl> / * <nl> * call - seq : <nl> * Message . method_missing ( * args ) <nl> VALUE Message_alloc ( VALUE klass ) { <nl> * <nl> * msg . foo = 42 <nl> * puts msg . foo <nl> + * <nl> + * This method also provides read - only accessors for oneofs . If a oneof exists <nl> + * with name ' my_oneof ' , then msg . my_oneof will return a Ruby symbol equal to <nl> + * the name of the field in that oneof that is currently set , or nil if none . <nl> * / <nl> VALUE Message_method_missing ( int argc , VALUE * argv , VALUE _self ) { <nl> MessageHeader * self ; <nl> VALUE Message_method_missing ( int argc , VALUE * argv , VALUE _self ) { <nl> name_len - - ; <nl> } <nl> <nl> + / / Check for a oneof name first . <nl> + const upb_oneofdef * o = upb_msgdef_ntoo ( self - > descriptor - > msgdef , <nl> + name , name_len ) ; <nl> + if ( o ! = NULL ) { <nl> + if ( setter ) { <nl> + rb_raise ( rb_eRuntimeError , " Oneof accessors are read - only . " ) ; <nl> + } <nl> + return which_oneof_field ( self , o ) ; <nl> + } <nl> + <nl> + / / Otherwise , check for a field with that name . <nl> const upb_fielddef * f = upb_msgdef_ntof ( self - > descriptor - > msgdef , <nl> name , name_len ) ; <nl> <nl> mmm a / ruby / ext / google / protobuf_c / protobuf . c <nl> ppp b / ruby / ext / google / protobuf_c / protobuf . c <nl> void Init_protobuf_c ( ) { <nl> DescriptorPool_register ( protobuf ) ; <nl> Descriptor_register ( protobuf ) ; <nl> FieldDescriptor_register ( protobuf ) ; <nl> + OneofDescriptor_register ( protobuf ) ; <nl> EnumDescriptor_register ( protobuf ) ; <nl> MessageBuilderContext_register ( internal ) ; <nl> + OneofBuilderContext_register ( internal ) ; <nl> EnumBuilderContext_register ( internal ) ; <nl> Builder_register ( internal ) ; <nl> RepeatedField_register ( protobuf ) ; <nl> mmm a / ruby / ext / google / protobuf_c / protobuf . h <nl> ppp b / ruby / ext / google / protobuf_c / protobuf . h <nl> struct Descriptor ; <nl> struct FieldDescriptor ; <nl> struct EnumDescriptor ; <nl> struct MessageLayout ; <nl> + struct MessageField ; <nl> struct MessageHeader ; <nl> struct MessageBuilderContext ; <nl> struct EnumBuilderContext ; <nl> struct Builder ; <nl> typedef struct DescriptorPool DescriptorPool ; <nl> typedef struct Descriptor Descriptor ; <nl> typedef struct FieldDescriptor FieldDescriptor ; <nl> + typedef struct OneofDescriptor OneofDescriptor ; <nl> typedef struct EnumDescriptor EnumDescriptor ; <nl> typedef struct MessageLayout MessageLayout ; <nl> + typedef struct MessageField MessageField ; <nl> typedef struct MessageHeader MessageHeader ; <nl> typedef struct MessageBuilderContext MessageBuilderContext ; <nl> + typedef struct OneofBuilderContext OneofBuilderContext ; <nl> typedef struct EnumBuilderContext EnumBuilderContext ; <nl> typedef struct Builder Builder ; <nl> <nl> struct FieldDescriptor { <nl> const upb_fielddef * fielddef ; <nl> } ; <nl> <nl> + struct OneofDescriptor { <nl> + const upb_oneofdef * oneofdef ; <nl> + } ; <nl> + <nl> struct EnumDescriptor { <nl> const upb_enumdef * enumdef ; <nl> VALUE module ; / / begins as nil <nl> struct MessageBuilderContext { <nl> VALUE builder ; <nl> } ; <nl> <nl> + struct OneofBuilderContext { <nl> + VALUE descriptor ; <nl> + VALUE builder ; <nl> + } ; <nl> + <nl> struct EnumBuilderContext { <nl> VALUE enumdesc ; <nl> } ; <nl> extern VALUE cDescriptor ; <nl> extern VALUE cFieldDescriptor ; <nl> extern VALUE cEnumDescriptor ; <nl> extern VALUE cMessageBuilderContext ; <nl> + extern VALUE cOneofBuilderContext ; <nl> extern VALUE cEnumBuilderContext ; <nl> extern VALUE cBuilder ; <nl> <nl> VALUE Descriptor_name_set ( VALUE _self , VALUE str ) ; <nl> VALUE Descriptor_each ( VALUE _self ) ; <nl> VALUE Descriptor_lookup ( VALUE _self , VALUE name ) ; <nl> VALUE Descriptor_add_field ( VALUE _self , VALUE obj ) ; <nl> + VALUE Descriptor_add_oneof ( VALUE _self , VALUE obj ) ; <nl> + VALUE Descriptor_each_oneof ( VALUE _self ) ; <nl> + VALUE Descriptor_lookup_oneof ( VALUE _self , VALUE name ) ; <nl> VALUE Descriptor_msgclass ( VALUE _self ) ; <nl> extern const rb_data_type_t _Descriptor_type ; <nl> <nl> VALUE FieldDescriptor_set ( VALUE _self , VALUE msg_rb , VALUE value ) ; <nl> upb_fieldtype_t ruby_to_fieldtype ( VALUE type ) ; <nl> VALUE fieldtype_to_ruby ( upb_fieldtype_t type ) ; <nl> <nl> + void OneofDescriptor_mark ( void * _self ) ; <nl> + void OneofDescriptor_free ( void * _self ) ; <nl> + VALUE OneofDescriptor_alloc ( VALUE klass ) ; <nl> + void OneofDescriptor_register ( VALUE module ) ; <nl> + OneofDescriptor * ruby_to_OneofDescriptor ( VALUE value ) ; <nl> + VALUE OneofDescriptor_name ( VALUE _self ) ; <nl> + VALUE OneofDescriptor_name_set ( VALUE _self , VALUE value ) ; <nl> + VALUE OneofDescriptor_add_field ( VALUE _self , VALUE field ) ; <nl> + VALUE OneofDescriptor_each ( VALUE _self , VALUE field ) ; <nl> + <nl> void EnumDescriptor_mark ( void * _self ) ; <nl> void EnumDescriptor_free ( void * _self ) ; <nl> VALUE EnumDescriptor_alloc ( VALUE klass ) ; <nl> VALUE MessageBuilderContext_optional ( int argc , VALUE * argv , VALUE _self ) ; <nl> VALUE MessageBuilderContext_required ( int argc , VALUE * argv , VALUE _self ) ; <nl> VALUE MessageBuilderContext_repeated ( int argc , VALUE * argv , VALUE _self ) ; <nl> VALUE MessageBuilderContext_map ( int argc , VALUE * argv , VALUE _self ) ; <nl> + VALUE MessageBuilderContext_oneof ( VALUE _self , VALUE name ) ; <nl> + <nl> + void OneofBuilderContext_mark ( void * _self ) ; <nl> + void OneofBuilderContext_free ( void * _self ) ; <nl> + VALUE OneofBuilderContext_alloc ( VALUE klass ) ; <nl> + void OneofBuilderContext_register ( VALUE module ) ; <nl> + OneofBuilderContext * ruby_to_OneofBuilderContext ( VALUE value ) ; <nl> + VALUE OneofBuilderContext_initialize ( VALUE _self , <nl> + VALUE descriptor , <nl> + VALUE builder ) ; <nl> + VALUE OneofBuilderContext_optional ( int argc , VALUE * argv , VALUE _self ) ; <nl> <nl> void EnumBuilderContext_mark ( void * _self ) ; <nl> void EnumBuilderContext_free ( void * _self ) ; <nl> VALUE Builder_finalize_to_pool ( VALUE _self , VALUE pool_rb ) ; <nl> / / Native slot storage abstraction . <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> <nl> - # define NATIVE_SLOT_MAX_SIZE sizeof ( void * ) <nl> + # define NATIVE_SLOT_MAX_SIZE sizeof ( uint64_t ) <nl> <nl> size_t native_slot_size ( upb_fieldtype_t type ) ; <nl> void native_slot_set ( upb_fieldtype_t type , <nl> VALUE type_class , <nl> void * memory , <nl> VALUE value ) ; <nl> + / / Atomically ( with respect to Ruby VM calls ) either update the value and set a <nl> + / / oneof case , or do neither . If | case_memory | is null , then no case value is <nl> + / / set . <nl> + void native_slot_set_value_and_case ( upb_fieldtype_t type , <nl> + VALUE type_class , <nl> + void * memory , <nl> + VALUE value , <nl> + uint32_t * case_memory , <nl> + uint32_t case_number ) ; <nl> VALUE native_slot_get ( upb_fieldtype_t type , <nl> VALUE type_class , <nl> const void * memory ) ; <nl> VALUE field_type_class ( const upb_fielddef * field ) ; <nl> # define MAP_KEY_FIELD 1 <nl> # define MAP_VALUE_FIELD 2 <nl> <nl> + / / Oneof case slot value to indicate that no oneof case is set . The value ` 0 ` is <nl> + / / safe because field numbers are used as case identifiers , and no field can <nl> + / / have a number of 0 . <nl> + # define ONEOF_CASE_NONE 0 <nl> + <nl> / / These operate on a map field ( i . e . , a repeated field of submessages whose <nl> / / submessage type is a map - entry msgdef ) . <nl> bool is_map_field ( const upb_fielddef * field ) ; <nl> VALUE Map_iter_value ( Map_iter * iter ) ; <nl> / / Message layout / storage . <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> <nl> + # define MESSAGE_FIELD_NO_CASE ( ( size_t ) - 1 ) <nl> + <nl> + struct MessageField { <nl> + size_t offset ; <nl> + size_t case_offset ; / / for oneofs , a uint32 . Else , MESSAGE_FIELD_NO_CASE . <nl> + } ; <nl> + <nl> struct MessageLayout { <nl> const upb_msgdef * msgdef ; <nl> - size_t * offsets ; <nl> + MessageField * fields ; <nl> size_t size ; <nl> } ; <nl> <nl> mmm a / ruby / ext / google / protobuf_c / storage . c <nl> ppp b / ruby / ext / google / protobuf_c / storage . c <nl> void native_slot_validate_string_encoding ( upb_fieldtype_t type , VALUE value ) { <nl> <nl> void native_slot_set ( upb_fieldtype_t type , VALUE type_class , <nl> void * memory , VALUE value ) { <nl> + native_slot_set_value_and_case ( type , type_class , memory , value , NULL , 0 ) ; <nl> + } <nl> + <nl> + void native_slot_set_value_and_case ( upb_fieldtype_t type , VALUE type_class , <nl> + void * memory , VALUE value , <nl> + uint32_t * case_memory , <nl> + uint32_t case_number ) { <nl> + / / Note that in order to atomically change the value in memory and the case <nl> + / / value ( w . r . t . Ruby VM calls ) , we must set the value at | memory | only after <nl> + / / all Ruby VM calls are complete . The case is then set at the bottom of this <nl> + / / function . <nl> switch ( type ) { <nl> case UPB_TYPE_FLOAT : <nl> if ( ! is_ruby_num ( value ) ) { <nl> void native_slot_set ( upb_fieldtype_t type , VALUE type_class , <nl> default : <nl> break ; <nl> } <nl> + <nl> + if ( case_memory ! = NULL ) { <nl> + * case_memory = case_number ; <nl> + } <nl> } <nl> <nl> VALUE native_slot_get ( upb_fieldtype_t type , <nl> const upb_fielddef * map_entry_value ( const upb_msgdef * msgdef ) { <nl> / / Memory layout management . <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> <nl> + static size_t align_up_to ( size_t offset , size_t granularity ) { <nl> + / / Granularity must be a power of two . <nl> + return ( offset + granularity - 1 ) & ~ ( granularity - 1 ) ; <nl> + } <nl> + <nl> MessageLayout * create_layout ( const upb_msgdef * msgdef ) { <nl> MessageLayout * layout = ALLOC ( MessageLayout ) ; <nl> int nfields = upb_msgdef_numfields ( msgdef ) ; <nl> - layout - > offsets = ALLOC_N ( size_t , nfields ) ; <nl> + layout - > fields = ALLOC_N ( MessageField , nfields ) ; <nl> <nl> - upb_msg_iter it ; <nl> + upb_msg_field_iter it ; <nl> size_t off = 0 ; <nl> - for ( upb_msg_begin ( & it , msgdef ) ; ! upb_msg_done ( & it ) ; upb_msg_next ( & it ) ) { <nl> + for ( upb_msg_field_begin ( & it , msgdef ) ; <nl> + ! upb_msg_field_done ( & it ) ; <nl> + upb_msg_field_next ( & it ) ) { <nl> const upb_fielddef * field = upb_msg_iter_field ( & it ) ; <nl> + <nl> + if ( upb_fielddef_containingoneof ( field ) ) { <nl> + / / Oneofs are handled separately below . <nl> + continue ; <nl> + } <nl> + <nl> + / / Allocate | field_size | bytes for this field in the layout . <nl> size_t field_size = 0 ; <nl> if ( upb_fielddef_label ( field ) = = UPB_LABEL_REPEATED ) { <nl> field_size = sizeof ( VALUE ) ; <nl> } else { <nl> field_size = native_slot_size ( upb_fielddef_type ( field ) ) ; <nl> } <nl> - / / align current offset <nl> + / / Align current offset up to | size | granularity . <nl> + off = align_up_to ( off , field_size ) ; <nl> + layout - > fields [ upb_fielddef_index ( field ) ] . offset = off ; <nl> + layout - > fields [ upb_fielddef_index ( field ) ] . case_offset = MESSAGE_FIELD_NO_CASE ; <nl> + off + = field_size ; <nl> + } <nl> + <nl> + / / Handle oneofs now - - we iterate over oneofs specifically and allocate only <nl> + / / one slot per oneof . <nl> + / / <nl> + / / We assign all value slots first , then pack the ' case ' fields at the end , <nl> + / / since in the common case ( modern 64 - bit platform ) these are 8 bytes and 4 <nl> + / / bytes respectively and we want to avoid alignment overhead . <nl> + / / <nl> + / / Note that we reserve 4 bytes ( a uint32 ) per ' case ' slot because the value <nl> + / / space for oneof cases is conceptually as wide as field tag numbers . In <nl> + / / practice , it ' s unlikely that a oneof would have more than e . g . 256 or 64K <nl> + / / members ( 8 or 16 bits respectively ) , so conceivably we could assign <nl> + / / consecutive case numbers and then pick a smaller oneof case slot size , but <nl> + / / the complexity to implement this indirection is probably not worthwhile . <nl> + upb_msg_oneof_iter oit ; <nl> + for ( upb_msg_oneof_begin ( & oit , msgdef ) ; <nl> + ! upb_msg_oneof_done ( & oit ) ; <nl> + upb_msg_oneof_next ( & oit ) ) { <nl> + const upb_oneofdef * oneof = upb_msg_iter_oneof ( & oit ) ; <nl> + <nl> + / / Always allocate NATIVE_SLOT_MAX_SIZE bytes , but share the slot between <nl> + / / all fields . <nl> + size_t field_size = NATIVE_SLOT_MAX_SIZE ; <nl> + / / Align the offset . <nl> + off = align_up_to ( off , field_size ) ; <nl> + / / Assign all fields in the oneof this same offset . <nl> + upb_oneof_iter fit ; <nl> + for ( upb_oneof_begin ( & fit , oneof ) ; <nl> + ! upb_oneof_done ( & fit ) ; <nl> + upb_oneof_next ( & fit ) ) { <nl> + const upb_fielddef * field = upb_oneof_iter_field ( & fit ) ; <nl> + layout - > fields [ upb_fielddef_index ( field ) ] . offset = off ; <nl> + } <nl> + off + = field_size ; <nl> + } <nl> + <nl> + / / Now the case fields . <nl> + for ( upb_msg_oneof_begin ( & oit , msgdef ) ; <nl> + ! upb_msg_oneof_done ( & oit ) ; <nl> + upb_msg_oneof_next ( & oit ) ) { <nl> + const upb_oneofdef * oneof = upb_msg_iter_oneof ( & oit ) ; <nl> + <nl> + size_t field_size = sizeof ( uint32_t ) ; <nl> + / / Align the offset . <nl> off = ( off + field_size - 1 ) & ~ ( field_size - 1 ) ; <nl> - layout - > offsets [ upb_fielddef_index ( field ) ] = off ; <nl> + / / Assign all fields in the oneof this same offset . <nl> + upb_oneof_iter fit ; <nl> + for ( upb_oneof_begin ( & fit , oneof ) ; <nl> + ! upb_oneof_done ( & fit ) ; <nl> + upb_oneof_next ( & fit ) ) { <nl> + const upb_fielddef * field = upb_oneof_iter_field ( & fit ) ; <nl> + layout - > fields [ upb_fielddef_index ( field ) ] . case_offset = off ; <nl> + } <nl> off + = field_size ; <nl> } <nl> <nl> MessageLayout * create_layout ( const upb_msgdef * msgdef ) { <nl> } <nl> <nl> void free_layout ( MessageLayout * layout ) { <nl> - xfree ( layout - > offsets ) ; <nl> + xfree ( layout - > fields ) ; <nl> upb_msgdef_unref ( layout - > msgdef , & layout - > msgdef ) ; <nl> xfree ( layout ) ; <nl> } <nl> VALUE field_type_class ( const upb_fielddef * field ) { <nl> return type_class ; <nl> } <nl> <nl> + static void * slot_memory ( MessageLayout * layout , <nl> + const void * storage , <nl> + const upb_fielddef * field ) { <nl> + return ( ( uint8_t * ) storage ) + <nl> + layout - > fields [ upb_fielddef_index ( field ) ] . offset ; <nl> + } <nl> + <nl> + static uint32_t * slot_oneof_case ( MessageLayout * layout , <nl> + const void * storage , <nl> + const upb_fielddef * field ) { <nl> + return ( uint32_t * ) ( ( ( uint8_t * ) storage ) + <nl> + layout - > fields [ upb_fielddef_index ( field ) ] . case_offset ) ; <nl> + } <nl> + <nl> + <nl> VALUE layout_get ( MessageLayout * layout , <nl> const void * storage , <nl> const upb_fielddef * field ) { <nl> - void * memory = ( ( uint8_t * ) storage ) + <nl> - layout - > offsets [ upb_fielddef_index ( field ) ] ; <nl> - if ( upb_fielddef_label ( field ) = = UPB_LABEL_REPEATED ) { <nl> + void * memory = slot_memory ( layout , storage , field ) ; <nl> + uint32_t * oneof_case = slot_oneof_case ( layout , storage , field ) ; <nl> + <nl> + if ( upb_fielddef_containingoneof ( field ) ) { <nl> + if ( * oneof_case ! = upb_fielddef_number ( field ) ) { <nl> + return Qnil ; <nl> + } <nl> + return native_slot_get ( upb_fielddef_type ( field ) , <nl> + field_type_class ( field ) , <nl> + memory ) ; <nl> + } else if ( upb_fielddef_label ( field ) = = UPB_LABEL_REPEATED ) { <nl> return * ( ( VALUE * ) memory ) ; <nl> } else { <nl> return native_slot_get ( upb_fielddef_type ( field ) , <nl> void layout_set ( MessageLayout * layout , <nl> void * storage , <nl> const upb_fielddef * field , <nl> VALUE val ) { <nl> - void * memory = ( ( uint8_t * ) storage ) + <nl> - layout - > offsets [ upb_fielddef_index ( field ) ] ; <nl> - if ( is_map_field ( field ) ) { <nl> + void * memory = slot_memory ( layout , storage , field ) ; <nl> + uint32_t * oneof_case = slot_oneof_case ( layout , storage , field ) ; <nl> + <nl> + if ( upb_fielddef_containingoneof ( field ) ) { <nl> + if ( val = = Qnil ) { <nl> + / / Assigning nil to a oneof field clears the oneof completely . <nl> + * oneof_case = ONEOF_CASE_NONE ; <nl> + memset ( memory , 0 , NATIVE_SLOT_MAX_SIZE ) ; <nl> + } else { <nl> + / / The transition between field types for a single oneof ( union ) slot is <nl> + / / somewhat complex because we need to ensure that a GC triggered at any <nl> + / / point by a call into the Ruby VM sees a valid state for this field and <nl> + / / does not either go off into the weeds ( following what it thinks is a <nl> + / / VALUE but is actually a different field type ) or miss an object ( seeing <nl> + / / what it thinks is a primitive field but is actually a VALUE for the new <nl> + / / field type ) . <nl> + / / <nl> + / / In order for the transition to be safe , the oneof case slot must be in <nl> + / / sync with the value slot whenever the Ruby VM has been called . Thus , we <nl> + / / use native_slot_set_value_and_case ( ) , which ensures that both the value <nl> + / / and case number are altered atomically ( w . r . t . the Ruby VM ) . <nl> + native_slot_set_value_and_case ( <nl> + upb_fielddef_type ( field ) , field_type_class ( field ) , <nl> + memory , val , <nl> + oneof_case , upb_fielddef_number ( field ) ) ; <nl> + } <nl> + } else if ( is_map_field ( field ) ) { <nl> check_map_field_type ( val , field ) ; <nl> DEREF ( memory , VALUE ) = val ; <nl> } else if ( upb_fielddef_label ( field ) = = UPB_LABEL_REPEATED ) { <nl> void layout_set ( MessageLayout * layout , <nl> <nl> void layout_init ( MessageLayout * layout , <nl> void * storage ) { <nl> - upb_msg_iter it ; <nl> - for ( upb_msg_begin ( & it , layout - > msgdef ) ; <nl> - ! upb_msg_done ( & it ) ; <nl> - upb_msg_next ( & it ) ) { <nl> + upb_msg_field_iter it ; <nl> + for ( upb_msg_field_begin ( & it , layout - > msgdef ) ; <nl> + ! upb_msg_field_done ( & it ) ; <nl> + upb_msg_field_next ( & it ) ) { <nl> const upb_fielddef * field = upb_msg_iter_field ( & it ) ; <nl> - void * memory = ( ( uint8_t * ) storage ) + <nl> - layout - > offsets [ upb_fielddef_index ( field ) ] ; <nl> + void * memory = slot_memory ( layout , storage , field ) ; <nl> + uint32_t * oneof_case = slot_oneof_case ( layout , storage , field ) ; <nl> <nl> - if ( is_map_field ( field ) ) { <nl> + if ( upb_fielddef_containingoneof ( field ) ) { <nl> + memset ( memory , 0 , NATIVE_SLOT_MAX_SIZE ) ; <nl> + * oneof_case = ONEOF_CASE_NONE ; <nl> + } else if ( is_map_field ( field ) ) { <nl> VALUE map = Qnil ; <nl> <nl> const upb_fielddef * key_field = map_field_key ( field ) ; <nl> void layout_init ( MessageLayout * layout , <nl> } <nl> <nl> void layout_mark ( MessageLayout * layout , void * storage ) { <nl> - upb_msg_iter it ; <nl> - for ( upb_msg_begin ( & it , layout - > msgdef ) ; <nl> - ! upb_msg_done ( & it ) ; <nl> - upb_msg_next ( & it ) ) { <nl> + upb_msg_field_iter it ; <nl> + for ( upb_msg_field_begin ( & it , layout - > msgdef ) ; <nl> + ! upb_msg_field_done ( & it ) ; <nl> + upb_msg_field_next ( & it ) ) { <nl> const upb_fielddef * field = upb_msg_iter_field ( & it ) ; <nl> - void * memory = ( ( uint8_t * ) storage ) + <nl> - layout - > offsets [ upb_fielddef_index ( field ) ] ; <nl> + void * memory = slot_memory ( layout , storage , field ) ; <nl> + uint32_t * oneof_case = slot_oneof_case ( layout , storage , field ) ; <nl> <nl> - if ( upb_fielddef_label ( field ) = = UPB_LABEL_REPEATED ) { <nl> + if ( upb_fielddef_containingoneof ( field ) ) { <nl> + if ( * oneof_case = = upb_fielddef_number ( field ) ) { <nl> + native_slot_mark ( upb_fielddef_type ( field ) , memory ) ; <nl> + } <nl> + } else if ( upb_fielddef_label ( field ) = = UPB_LABEL_REPEATED ) { <nl> rb_gc_mark ( DEREF ( memory , VALUE ) ) ; <nl> } else { <nl> native_slot_mark ( upb_fielddef_type ( field ) , memory ) ; <nl> void layout_mark ( MessageLayout * layout , void * storage ) { <nl> } <nl> <nl> void layout_dup ( MessageLayout * layout , void * to , void * from ) { <nl> - upb_msg_iter it ; <nl> - for ( upb_msg_begin ( & it , layout - > msgdef ) ; <nl> - ! upb_msg_done ( & it ) ; <nl> - upb_msg_next ( & it ) ) { <nl> + upb_msg_field_iter it ; <nl> + for ( upb_msg_field_begin ( & it , layout - > msgdef ) ; <nl> + ! upb_msg_field_done ( & it ) ; <nl> + upb_msg_field_next ( & it ) ) { <nl> const upb_fielddef * field = upb_msg_iter_field ( & it ) ; <nl> - void * to_memory = ( ( uint8_t * ) to ) + <nl> - layout - > offsets [ upb_fielddef_index ( field ) ] ; <nl> - void * from_memory = ( ( uint8_t * ) from ) + <nl> - layout - > offsets [ upb_fielddef_index ( field ) ] ; <nl> <nl> - if ( is_map_field ( field ) ) { <nl> + void * to_memory = slot_memory ( layout , to , field ) ; <nl> + uint32_t * to_oneof_case = slot_oneof_case ( layout , to , field ) ; <nl> + void * from_memory = slot_memory ( layout , from , field ) ; <nl> + uint32_t * from_oneof_case = slot_oneof_case ( layout , from , field ) ; <nl> + <nl> + if ( upb_fielddef_containingoneof ( field ) ) { <nl> + if ( * from_oneof_case = = upb_fielddef_number ( field ) ) { <nl> + * to_oneof_case = * from_oneof_case ; <nl> + native_slot_dup ( upb_fielddef_type ( field ) , to_memory , from_memory ) ; <nl> + } <nl> + } else if ( is_map_field ( field ) ) { <nl> DEREF ( to_memory , VALUE ) = Map_dup ( DEREF ( from_memory , VALUE ) ) ; <nl> } else if ( upb_fielddef_label ( field ) = = UPB_LABEL_REPEATED ) { <nl> DEREF ( to_memory , VALUE ) = RepeatedField_dup ( DEREF ( from_memory , VALUE ) ) ; <nl> void layout_dup ( MessageLayout * layout , void * to , void * from ) { <nl> } <nl> <nl> void layout_deep_copy ( MessageLayout * layout , void * to , void * from ) { <nl> - upb_msg_iter it ; <nl> - for ( upb_msg_begin ( & it , layout - > msgdef ) ; <nl> - ! upb_msg_done ( & it ) ; <nl> - upb_msg_next ( & it ) ) { <nl> + upb_msg_field_iter it ; <nl> + for ( upb_msg_field_begin ( & it , layout - > msgdef ) ; <nl> + ! upb_msg_field_done ( & it ) ; <nl> + upb_msg_field_next ( & it ) ) { <nl> const upb_fielddef * field = upb_msg_iter_field ( & it ) ; <nl> - void * to_memory = ( ( uint8_t * ) to ) + <nl> - layout - > offsets [ upb_fielddef_index ( field ) ] ; <nl> - void * from_memory = ( ( uint8_t * ) from ) + <nl> - layout - > offsets [ upb_fielddef_index ( field ) ] ; <nl> <nl> - if ( is_map_field ( field ) ) { <nl> + void * to_memory = slot_memory ( layout , to , field ) ; <nl> + uint32_t * to_oneof_case = slot_oneof_case ( layout , to , field ) ; <nl> + void * from_memory = slot_memory ( layout , from , field ) ; <nl> + uint32_t * from_oneof_case = slot_oneof_case ( layout , from , field ) ; <nl> + <nl> + if ( upb_fielddef_containingoneof ( field ) ) { <nl> + if ( * from_oneof_case = = upb_fielddef_number ( field ) ) { <nl> + * to_oneof_case = * from_oneof_case ; <nl> + native_slot_deep_copy ( upb_fielddef_type ( field ) , to_memory , from_memory ) ; <nl> + } <nl> + } else if ( is_map_field ( field ) ) { <nl> DEREF ( to_memory , VALUE ) = <nl> Map_deep_copy ( DEREF ( from_memory , VALUE ) ) ; <nl> } else if ( upb_fielddef_label ( field ) = = UPB_LABEL_REPEATED ) { <nl> void layout_deep_copy ( MessageLayout * layout , void * to , void * from ) { <nl> } <nl> <nl> VALUE layout_eq ( MessageLayout * layout , void * msg1 , void * msg2 ) { <nl> - upb_msg_iter it ; <nl> - for ( upb_msg_begin ( & it , layout - > msgdef ) ; <nl> - ! upb_msg_done ( & it ) ; <nl> - upb_msg_next ( & it ) ) { <nl> + upb_msg_field_iter it ; <nl> + for ( upb_msg_field_begin ( & it , layout - > msgdef ) ; <nl> + ! upb_msg_field_done ( & it ) ; <nl> + upb_msg_field_next ( & it ) ) { <nl> const upb_fielddef * field = upb_msg_iter_field ( & it ) ; <nl> - void * msg1_memory = ( ( uint8_t * ) msg1 ) + <nl> - layout - > offsets [ upb_fielddef_index ( field ) ] ; <nl> - void * msg2_memory = ( ( uint8_t * ) msg2 ) + <nl> - layout - > offsets [ upb_fielddef_index ( field ) ] ; <nl> - <nl> - if ( is_map_field ( field ) ) { <nl> - return Map_eq ( DEREF ( msg1_memory , VALUE ) , <nl> - DEREF ( msg2_memory , VALUE ) ) ; <nl> + <nl> + void * msg1_memory = slot_memory ( layout , msg1 , field ) ; <nl> + uint32_t * msg1_oneof_case = slot_oneof_case ( layout , msg1 , field ) ; <nl> + void * msg2_memory = slot_memory ( layout , msg2 , field ) ; <nl> + uint32_t * msg2_oneof_case = slot_oneof_case ( layout , msg2 , field ) ; <nl> + <nl> + if ( upb_fielddef_containingoneof ( field ) ) { <nl> + if ( * msg1_oneof_case ! = * msg2_oneof_case | | <nl> + ( * msg1_oneof_case = = upb_fielddef_number ( field ) & & <nl> + ! native_slot_eq ( upb_fielddef_type ( field ) , <nl> + msg1_memory , <nl> + msg2_memory ) ) ) { <nl> + return Qfalse ; <nl> + } <nl> + } else if ( is_map_field ( field ) ) { <nl> + if ( ! Map_eq ( DEREF ( msg1_memory , VALUE ) , <nl> + DEREF ( msg2_memory , VALUE ) ) ) { <nl> + return Qfalse ; <nl> + } <nl> } else if ( upb_fielddef_label ( field ) = = UPB_LABEL_REPEATED ) { <nl> - return RepeatedField_eq ( DEREF ( msg1_memory , VALUE ) , <nl> - DEREF ( msg2_memory , VALUE ) ) ; <nl> + if ( ! RepeatedField_eq ( DEREF ( msg1_memory , VALUE ) , <nl> + DEREF ( msg2_memory , VALUE ) ) ) { <nl> + return Qfalse ; <nl> + } <nl> } else { <nl> if ( ! native_slot_eq ( upb_fielddef_type ( field ) , <nl> msg1_memory , msg2_memory ) ) { <nl> VALUE layout_eq ( MessageLayout * layout , void * msg1 , void * msg2 ) { <nl> } <nl> <nl> VALUE layout_hash ( MessageLayout * layout , void * storage ) { <nl> - upb_msg_iter it ; <nl> + upb_msg_field_iter it ; <nl> st_index_t h = rb_hash_start ( 0 ) ; <nl> VALUE hash_sym = rb_intern ( " hash " ) ; <nl> - for ( upb_msg_begin ( & it , layout - > msgdef ) ; <nl> - ! upb_msg_done ( & it ) ; <nl> - upb_msg_next ( & it ) ) { <nl> + for ( upb_msg_field_begin ( & it , layout - > msgdef ) ; <nl> + ! upb_msg_field_done ( & it ) ; <nl> + upb_msg_field_next ( & it ) ) { <nl> const upb_fielddef * field = upb_msg_iter_field ( & it ) ; <nl> VALUE field_val = layout_get ( layout , storage , field ) ; <nl> h = rb_hash_uint ( h , NUM2LONG ( rb_funcall ( field_val , hash_sym , 0 ) ) ) ; <nl> VALUE layout_hash ( MessageLayout * layout , void * storage ) { <nl> VALUE layout_inspect ( MessageLayout * layout , void * storage ) { <nl> VALUE str = rb_str_new2 ( " " ) ; <nl> <nl> - upb_msg_iter it ; <nl> + upb_msg_field_iter it ; <nl> bool first = true ; <nl> - for ( upb_msg_begin ( & it , layout - > msgdef ) ; <nl> - ! upb_msg_done ( & it ) ; <nl> - upb_msg_next ( & it ) ) { <nl> + for ( upb_msg_field_begin ( & it , layout - > msgdef ) ; <nl> + ! upb_msg_field_done ( & it ) ; <nl> + upb_msg_field_next ( & it ) ) { <nl> const upb_fielddef * field = upb_msg_iter_field ( & it ) ; <nl> VALUE field_val = layout_get ( layout , storage , field ) ; <nl> <nl> mmm a / ruby / ext / google / protobuf_c / upb . c <nl> ppp b / ruby / ext / google / protobuf_c / upb . c <nl> static bool assign_msg_indices ( upb_msgdef * m , upb_status * s ) { <nl> upb_fielddef * * fields = malloc ( n * sizeof ( * fields ) ) ; <nl> if ( ! fields ) return false ; <nl> <nl> - upb_msg_iter j ; <nl> + upb_msg_field_iter j ; <nl> int i ; <nl> m - > submsg_field_count = 0 ; <nl> - for ( i = 0 , upb_msg_begin ( & j , m ) ; ! upb_msg_done ( & j ) ; upb_msg_next ( & j ) , i + + ) { <nl> + for ( i = 0 , upb_msg_field_begin ( & j , m ) ; <nl> + ! upb_msg_field_done ( & j ) ; <nl> + upb_msg_field_next ( & j ) , i + + ) { <nl> upb_fielddef * f = upb_msg_iter_field ( & j ) ; <nl> assert ( f - > msg . def = = m ) ; <nl> if ( ! upb_validate_field ( f , s ) ) { <nl> static bool assign_msg_indices ( upb_msgdef * m , upb_status * s ) { <nl> upb_selector_t sel ; <nl> upb_inttable_insert ( & t , UPB_STARTMSG_SELECTOR , v ) ; <nl> upb_inttable_insert ( & t , UPB_ENDMSG_SELECTOR , v ) ; <nl> - for ( upb_msg_begin ( & j , m ) ; ! upb_msg_done ( & j ) ; upb_msg_next ( & j ) ) { <nl> + for ( upb_msg_field_begin ( & j , m ) ; <nl> + ! upb_msg_field_done ( & j ) ; <nl> + upb_msg_field_next ( & j ) ) { <nl> upb_fielddef * f = upb_msg_iter_field ( & j ) ; <nl> / / These calls will assert - fail in upb_table if the value already exists . <nl> TRY ( UPB_HANDLER_INT32 ) ; <nl> static void visitfield ( const upb_refcounted * r , upb_refcounted_visit * visit , <nl> if ( upb_fielddef_containingtype ( f ) ) { <nl> visit ( r , UPB_UPCAST2 ( upb_fielddef_containingtype ( f ) ) , closure ) ; <nl> } <nl> + if ( upb_fielddef_containingoneof ( f ) ) { <nl> + visit ( r , UPB_UPCAST2 ( upb_fielddef_containingoneof ( f ) ) , closure ) ; <nl> + } <nl> if ( upb_fielddef_subdef ( f ) ) { <nl> visit ( r , UPB_UPCAST ( upb_fielddef_subdef ( f ) ) , closure ) ; <nl> } <nl> upb_fielddef * upb_fielddef_new ( const void * owner ) { <nl> } <nl> f - > msg . def = NULL ; <nl> f - > sub . def = NULL ; <nl> + f - > oneof = NULL ; <nl> f - > subdef_is_symbolic = false ; <nl> f - > msg_is_symbolic = false ; <nl> f - > label_ = UPB_LABEL_OPTIONAL ; <nl> const upb_msgdef * upb_fielddef_containingtype ( const upb_fielddef * f ) { <nl> return f - > msg_is_symbolic ? NULL : f - > msg . def ; <nl> } <nl> <nl> + const upb_oneofdef * upb_fielddef_containingoneof ( const upb_fielddef * f ) { <nl> + return f - > oneof ; <nl> + } <nl> + <nl> upb_msgdef * upb_fielddef_containingtype_mutable ( upb_fielddef * f ) { <nl> return ( upb_msgdef * ) upb_fielddef_containingtype ( f ) ; <nl> } <nl> bool upb_fielddef_setcontainingtypename ( upb_fielddef * f , const char * name , <nl> } <nl> <nl> bool upb_fielddef_setname ( upb_fielddef * f , const char * name , upb_status * s ) { <nl> + if ( upb_fielddef_containingtype ( f ) | | upb_fielddef_containingoneof ( f ) ) { <nl> + upb_status_seterrmsg ( s , " Already added to message or oneof " ) ; <nl> + return false ; <nl> + } <nl> return upb_def_setfullname ( UPB_UPCAST ( f ) , name , s ) ; <nl> } <nl> <nl> bool upb_fielddef_checkdescriptortype ( int32_t type ) { <nl> static void visitmsg ( const upb_refcounted * r , upb_refcounted_visit * visit , <nl> void * closure ) { <nl> const upb_msgdef * m = ( const upb_msgdef * ) r ; <nl> - upb_msg_iter i ; <nl> - for ( upb_msg_begin ( & i , m ) ; ! upb_msg_done ( & i ) ; upb_msg_next ( & i ) ) { <nl> + upb_msg_field_iter i ; <nl> + for ( upb_msg_field_begin ( & i , m ) ; <nl> + ! upb_msg_field_done ( & i ) ; <nl> + upb_msg_field_next ( & i ) ) { <nl> upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> visit ( r , UPB_UPCAST2 ( f ) , closure ) ; <nl> } <nl> + upb_msg_oneof_iter o ; <nl> + for ( upb_msg_oneof_begin ( & o , m ) ; <nl> + ! upb_msg_oneof_done ( & o ) ; <nl> + upb_msg_oneof_next ( & o ) ) { <nl> + upb_oneofdef * f = upb_msg_iter_oneof ( & o ) ; <nl> + visit ( r , UPB_UPCAST2 ( f ) , closure ) ; <nl> + } <nl> } <nl> <nl> static void freemsg ( upb_refcounted * r ) { <nl> upb_msgdef * m = ( upb_msgdef * ) r ; <nl> + upb_strtable_uninit ( & m - > ntoo ) ; <nl> upb_strtable_uninit ( & m - > ntof ) ; <nl> upb_inttable_uninit ( & m - > itof ) ; <nl> upb_def_uninit ( UPB_UPCAST ( m ) ) ; <nl> upb_msgdef * upb_msgdef_new ( const void * owner ) { <nl> upb_msgdef * m = malloc ( sizeof ( * m ) ) ; <nl> if ( ! m ) return NULL ; <nl> if ( ! upb_def_init ( UPB_UPCAST ( m ) , UPB_DEF_MSG , & vtbl , owner ) ) goto err2 ; <nl> - if ( ! upb_inttable_init ( & m - > itof , UPB_CTYPE_PTR ) ) goto err2 ; <nl> - if ( ! upb_strtable_init ( & m - > ntof , UPB_CTYPE_PTR ) ) goto err1 ; <nl> + if ( ! upb_inttable_init ( & m - > itof , UPB_CTYPE_PTR ) ) goto err3 ; <nl> + if ( ! upb_strtable_init ( & m - > ntof , UPB_CTYPE_PTR ) ) goto err2 ; <nl> + if ( ! upb_strtable_init ( & m - > ntoo , UPB_CTYPE_PTR ) ) goto err1 ; <nl> m - > map_entry = false ; <nl> return m ; <nl> <nl> err1 : <nl> - upb_inttable_uninit ( & m - > itof ) ; <nl> + upb_strtable_uninit ( & m - > ntof ) ; <nl> err2 : <nl> + upb_inttable_uninit ( & m - > itof ) ; <nl> + err3 : <nl> free ( m ) ; <nl> return NULL ; <nl> } <nl> upb_msgdef * upb_msgdef_dup ( const upb_msgdef * m , const void * owner ) { <nl> upb_def_fullname ( UPB_UPCAST ( m ) ) , NULL ) ; <nl> newm - > map_entry = m - > map_entry ; <nl> UPB_ASSERT_VAR ( ok , ok ) ; <nl> - upb_msg_iter i ; <nl> - for ( upb_msg_begin ( & i , m ) ; ! upb_msg_done ( & i ) ; upb_msg_next ( & i ) ) { <nl> + upb_msg_field_iter i ; <nl> + for ( upb_msg_field_begin ( & i , m ) ; <nl> + ! upb_msg_field_done ( & i ) ; <nl> + upb_msg_field_next ( & i ) ) { <nl> upb_fielddef * f = upb_fielddef_dup ( upb_msg_iter_field ( & i ) , & f ) ; <nl> + / / Fields in oneofs are dup ' d below . <nl> + if ( upb_fielddef_containingoneof ( f ) ) continue ; <nl> if ( ! f | | ! upb_msgdef_addfield ( newm , f , & f , NULL ) ) { <nl> upb_msgdef_unref ( newm , owner ) ; <nl> return NULL ; <nl> } <nl> } <nl> + upb_msg_oneof_iter o ; <nl> + for ( upb_msg_oneof_begin ( & o , m ) ; <nl> + ! upb_msg_oneof_done ( & o ) ; <nl> + upb_msg_oneof_next ( & o ) ) { <nl> + upb_oneofdef * f = upb_oneofdef_dup ( upb_msg_iter_oneof ( & o ) , & f ) ; <nl> + if ( ! f | | ! upb_msgdef_addoneof ( newm , f , & f , NULL ) ) { <nl> + upb_msgdef_unref ( newm , owner ) ; <nl> + return NULL ; <nl> + } <nl> + } <nl> return newm ; <nl> } <nl> <nl> bool upb_msgdef_setfullname ( upb_msgdef * m , const char * fullname , <nl> return upb_def_setfullname ( UPB_UPCAST ( m ) , fullname , s ) ; <nl> } <nl> <nl> + / / Helper : check that the field | f | is safe to add to msgdef | m | . Set an error <nl> + / / on status | s | and return false if not . <nl> + static bool check_field_add ( const upb_msgdef * m , const upb_fielddef * f , <nl> + upb_status * s ) { <nl> + if ( upb_fielddef_containingtype ( f ) ! = NULL ) { <nl> + upb_status_seterrmsg ( s , " fielddef already belongs to a message " ) ; <nl> + return false ; <nl> + } else if ( upb_fielddef_name ( f ) = = NULL | | upb_fielddef_number ( f ) = = 0 ) { <nl> + upb_status_seterrmsg ( s , " field name or number were not set " ) ; <nl> + return false ; <nl> + } else if ( upb_msgdef_ntofz ( m , upb_fielddef_name ( f ) ) | | <nl> + upb_msgdef_itof ( m , upb_fielddef_number ( f ) ) ) { <nl> + upb_status_seterrmsg ( s , " duplicate field name or number for field " ) ; <nl> + return false ; <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + static void add_field ( upb_msgdef * m , upb_fielddef * f , const void * ref_donor ) { <nl> + release_containingtype ( f ) ; <nl> + f - > msg . def = m ; <nl> + f - > msg_is_symbolic = false ; <nl> + upb_inttable_insert ( & m - > itof , upb_fielddef_number ( f ) , upb_value_ptr ( f ) ) ; <nl> + upb_strtable_insert ( & m - > ntof , upb_fielddef_name ( f ) , upb_value_ptr ( f ) ) ; <nl> + upb_ref2 ( f , m ) ; <nl> + upb_ref2 ( m , f ) ; <nl> + if ( ref_donor ) upb_fielddef_unref ( f , ref_donor ) ; <nl> + } <nl> + <nl> bool upb_msgdef_addfield ( upb_msgdef * m , upb_fielddef * f , const void * ref_donor , <nl> upb_status * s ) { <nl> / / TODO : extensions need to have a separate namespace , because proto2 allows a <nl> bool upb_msgdef_addfield ( upb_msgdef * m , upb_fielddef * f , const void * ref_donor , <nl> / / We also need to validate that the field number is in an extension range iff <nl> / / it is an extension . <nl> <nl> + / / This method is idempotent . Check if | f | is already part of this msgdef and <nl> + / / return immediately if so . <nl> + if ( upb_fielddef_containingtype ( f ) = = m ) { <nl> + return true ; <nl> + } <nl> + <nl> / / Check constraints for all fields before performing any action . <nl> - if ( upb_fielddef_containingtype ( f ) ! = NULL ) { <nl> - upb_status_seterrmsg ( s , " fielddef already belongs to a message " ) ; <nl> - return false ; <nl> - } else if ( upb_fielddef_name ( f ) = = NULL | | upb_fielddef_number ( f ) = = 0 ) { <nl> - upb_status_seterrmsg ( s , " field name or number were not set " ) ; <nl> + if ( ! check_field_add ( m , f , s ) ) { <nl> return false ; <nl> - } else if ( upb_msgdef_itof ( m , upb_fielddef_number ( f ) ) | | <nl> - upb_msgdef_ntofz ( m , upb_fielddef_name ( f ) ) ) { <nl> - upb_status_seterrmsg ( s , " duplicate field name or number " ) ; <nl> + } else if ( upb_fielddef_containingoneof ( f ) ! = NULL ) { <nl> + / / Fields in a oneof can only be added by adding the oneof to the msgdef . <nl> + upb_status_seterrmsg ( s , " fielddef is part of a oneof " ) ; <nl> return false ; <nl> } <nl> <nl> / / Constraint checks ok , perform the action . <nl> - release_containingtype ( f ) ; <nl> - f - > msg . def = m ; <nl> - f - > msg_is_symbolic = false ; <nl> - upb_inttable_insert ( & m - > itof , upb_fielddef_number ( f ) , upb_value_ptr ( f ) ) ; <nl> - upb_strtable_insert ( & m - > ntof , upb_fielddef_name ( f ) , upb_value_ptr ( f ) ) ; <nl> - upb_ref2 ( f , m ) ; <nl> - upb_ref2 ( m , f ) ; <nl> - if ( ref_donor ) upb_fielddef_unref ( f , ref_donor ) ; <nl> + add_field ( m , f , ref_donor ) ; <nl> + return true ; <nl> + } <nl> + <nl> + bool upb_msgdef_addoneof ( upb_msgdef * m , upb_oneofdef * o , const void * ref_donor , <nl> + upb_status * s ) { <nl> + / / Check various conditions that would prevent this oneof from being added . <nl> + if ( upb_oneofdef_containingtype ( o ) ) { <nl> + upb_status_seterrmsg ( s , " oneofdef already belongs to a message " ) ; <nl> + return false ; <nl> + } else if ( upb_oneofdef_name ( o ) = = NULL ) { <nl> + upb_status_seterrmsg ( s , " oneofdef name was not set " ) ; <nl> + return false ; <nl> + } else if ( upb_msgdef_ntooz ( m , upb_oneofdef_name ( o ) ) ) { <nl> + upb_status_seterrmsg ( s , " duplicate oneof name " ) ; <nl> + return false ; <nl> + } <nl> + <nl> + / / Check that all of the oneof ' s fields do not conflict with names or numbers <nl> + / / of fields already in the message . <nl> + upb_oneof_iter it ; <nl> + for ( upb_oneof_begin ( & it , o ) ; ! upb_oneof_done ( & it ) ; upb_oneof_next ( & it ) ) { <nl> + const upb_fielddef * f = upb_oneof_iter_field ( & it ) ; <nl> + if ( ! check_field_add ( m , f , s ) ) { <nl> + return false ; <nl> + } <nl> + } <nl> + <nl> + / / Everything checks out - - commit now . <nl> + <nl> + / / Add oneof itself first . <nl> + o - > parent = m ; <nl> + upb_strtable_insert ( & m - > ntoo , upb_oneofdef_name ( o ) , upb_value_ptr ( o ) ) ; <nl> + upb_ref2 ( o , m ) ; <nl> + upb_ref2 ( m , o ) ; <nl> + <nl> + / / Add each field of the oneof directly to the msgdef . <nl> + for ( upb_oneof_begin ( & it , o ) ; ! upb_oneof_done ( & it ) ; upb_oneof_next ( & it ) ) { <nl> + upb_fielddef * f = upb_oneof_iter_field ( & it ) ; <nl> + add_field ( m , f , NULL ) ; <nl> + } <nl> + <nl> + if ( ref_donor ) upb_oneofdef_unref ( o , ref_donor ) ; <nl> <nl> return true ; <nl> } <nl> const upb_fielddef * upb_msgdef_ntof ( const upb_msgdef * m , const char * name , <nl> upb_value_getptr ( val ) : NULL ; <nl> } <nl> <nl> + const upb_oneofdef * upb_msgdef_ntoo ( const upb_msgdef * m , const char * name , <nl> + size_t len ) { <nl> + upb_value val ; <nl> + return upb_strtable_lookup2 ( & m - > ntoo , name , len , & val ) ? <nl> + upb_value_getptr ( val ) : NULL ; <nl> + } <nl> + <nl> int upb_msgdef_numfields ( const upb_msgdef * m ) { <nl> return upb_strtable_count ( & m - > ntof ) ; <nl> } <nl> <nl> + int upb_msgdef_numoneofs ( const upb_msgdef * m ) { <nl> + return upb_strtable_count ( & m - > ntoo ) ; <nl> + } <nl> + <nl> void upb_msgdef_setmapentry ( upb_msgdef * m , bool map_entry ) { <nl> assert ( ! upb_msgdef_isfrozen ( m ) ) ; <nl> m - > map_entry = map_entry ; <nl> bool upb_msgdef_mapentry ( const upb_msgdef * m ) { <nl> return m - > map_entry ; <nl> } <nl> <nl> - void upb_msg_begin ( upb_msg_iter * iter , const upb_msgdef * m ) { <nl> + void upb_msg_field_begin ( upb_msg_field_iter * iter , const upb_msgdef * m ) { <nl> upb_inttable_begin ( iter , & m - > itof ) ; <nl> } <nl> <nl> - void upb_msg_next ( upb_msg_iter * iter ) { upb_inttable_next ( iter ) ; } <nl> + void upb_msg_field_next ( upb_msg_field_iter * iter ) { upb_inttable_next ( iter ) ; } <nl> <nl> - bool upb_msg_done ( const upb_msg_iter * iter ) { return upb_inttable_done ( iter ) ; } <nl> + bool upb_msg_field_done ( const upb_msg_field_iter * iter ) { <nl> + return upb_inttable_done ( iter ) ; <nl> + } <nl> <nl> - upb_fielddef * upb_msg_iter_field ( const upb_msg_iter * iter ) { <nl> + upb_fielddef * upb_msg_iter_field ( const upb_msg_field_iter * iter ) { <nl> return ( upb_fielddef * ) upb_value_getptr ( upb_inttable_iter_value ( iter ) ) ; <nl> } <nl> <nl> - void upb_msg_iter_setdone ( upb_msg_iter * iter ) { <nl> + void upb_msg_field_iter_setdone ( upb_msg_field_iter * iter ) { <nl> + upb_inttable_iter_setdone ( iter ) ; <nl> + } <nl> + <nl> + void upb_msg_oneof_begin ( upb_msg_oneof_iter * iter , const upb_msgdef * m ) { <nl> + upb_strtable_begin ( iter , & m - > ntoo ) ; <nl> + } <nl> + <nl> + void upb_msg_oneof_next ( upb_msg_oneof_iter * iter ) { upb_strtable_next ( iter ) ; } <nl> + <nl> + bool upb_msg_oneof_done ( const upb_msg_oneof_iter * iter ) { <nl> + return upb_strtable_done ( iter ) ; <nl> + } <nl> + <nl> + upb_oneofdef * upb_msg_iter_oneof ( const upb_msg_oneof_iter * iter ) { <nl> + return ( upb_oneofdef * ) upb_value_getptr ( upb_strtable_iter_value ( iter ) ) ; <nl> + } <nl> + <nl> + void upb_msg_oneof_iter_setdone ( upb_msg_oneof_iter * iter ) { <nl> + upb_strtable_iter_setdone ( iter ) ; <nl> + } <nl> + <nl> + / * upb_oneofdef * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + static void visitoneof ( const upb_refcounted * r , upb_refcounted_visit * visit , <nl> + void * closure ) { <nl> + const upb_oneofdef * o = ( const upb_oneofdef * ) r ; <nl> + upb_oneof_iter i ; <nl> + for ( upb_oneof_begin ( & i , o ) ; ! upb_oneof_done ( & i ) ; upb_oneof_next ( & i ) ) { <nl> + const upb_fielddef * f = upb_oneof_iter_field ( & i ) ; <nl> + visit ( r , UPB_UPCAST2 ( f ) , closure ) ; <nl> + } <nl> + if ( o - > parent ) { <nl> + visit ( r , UPB_UPCAST2 ( o - > parent ) , closure ) ; <nl> + } <nl> + } <nl> + <nl> + static void freeoneof ( upb_refcounted * r ) { <nl> + upb_oneofdef * o = ( upb_oneofdef * ) r ; <nl> + upb_strtable_uninit ( & o - > ntof ) ; <nl> + upb_inttable_uninit ( & o - > itof ) ; <nl> + upb_def_uninit ( UPB_UPCAST ( o ) ) ; <nl> + free ( o ) ; <nl> + } <nl> + <nl> + upb_oneofdef * upb_oneofdef_new ( const void * owner ) { <nl> + static const struct upb_refcounted_vtbl vtbl = { visitoneof , freeoneof } ; <nl> + upb_oneofdef * o = malloc ( sizeof ( * o ) ) ; <nl> + o - > parent = NULL ; <nl> + if ( ! o ) return NULL ; <nl> + if ( ! upb_def_init ( UPB_UPCAST ( o ) , UPB_DEF_ONEOF , & vtbl , owner ) ) goto err2 ; <nl> + if ( ! upb_inttable_init ( & o - > itof , UPB_CTYPE_PTR ) ) goto err2 ; <nl> + if ( ! upb_strtable_init ( & o - > ntof , UPB_CTYPE_PTR ) ) goto err1 ; <nl> + return o ; <nl> + <nl> + err1 : <nl> + upb_inttable_uninit ( & o - > itof ) ; <nl> + err2 : <nl> + free ( o ) ; <nl> + return NULL ; <nl> + } <nl> + <nl> + upb_oneofdef * upb_oneofdef_dup ( const upb_oneofdef * o , const void * owner ) { <nl> + upb_oneofdef * newo = upb_oneofdef_new ( owner ) ; <nl> + if ( ! newo ) return NULL ; <nl> + bool ok = upb_def_setfullname ( UPB_UPCAST ( newo ) , <nl> + upb_def_fullname ( UPB_UPCAST ( o ) ) , NULL ) ; <nl> + UPB_ASSERT_VAR ( ok , ok ) ; <nl> + upb_oneof_iter i ; <nl> + for ( upb_oneof_begin ( & i , o ) ; ! upb_oneof_done ( & i ) ; upb_oneof_next ( & i ) ) { <nl> + upb_fielddef * f = upb_fielddef_dup ( upb_oneof_iter_field ( & i ) , & f ) ; <nl> + if ( ! f | | ! upb_oneofdef_addfield ( newo , f , & f , NULL ) ) { <nl> + upb_oneofdef_unref ( newo , owner ) ; <nl> + return NULL ; <nl> + } <nl> + } <nl> + return newo ; <nl> + } <nl> + <nl> + bool upb_oneofdef_isfrozen ( const upb_oneofdef * o ) { <nl> + return upb_def_isfrozen ( UPB_UPCAST ( o ) ) ; <nl> + } <nl> + <nl> + void upb_oneofdef_ref ( const upb_oneofdef * o , const void * owner ) { <nl> + upb_def_ref ( UPB_UPCAST ( o ) , owner ) ; <nl> + } <nl> + <nl> + void upb_oneofdef_unref ( const upb_oneofdef * o , const void * owner ) { <nl> + upb_def_unref ( UPB_UPCAST ( o ) , owner ) ; <nl> + } <nl> + <nl> + void upb_oneofdef_donateref ( const upb_oneofdef * o , const void * from , <nl> + const void * to ) { <nl> + upb_def_donateref ( UPB_UPCAST ( o ) , from , to ) ; <nl> + } <nl> + <nl> + void upb_oneofdef_checkref ( const upb_oneofdef * o , const void * owner ) { <nl> + upb_def_checkref ( UPB_UPCAST ( o ) , owner ) ; <nl> + } <nl> + <nl> + const char * upb_oneofdef_name ( const upb_oneofdef * o ) { <nl> + return upb_def_fullname ( UPB_UPCAST ( o ) ) ; <nl> + } <nl> + <nl> + bool upb_oneofdef_setname ( upb_oneofdef * o , const char * fullname , <nl> + upb_status * s ) { <nl> + if ( upb_oneofdef_containingtype ( o ) ) { <nl> + upb_status_seterrmsg ( s , " oneof already added to a message " ) ; <nl> + return false ; <nl> + } <nl> + return upb_def_setfullname ( UPB_UPCAST ( o ) , fullname , s ) ; <nl> + } <nl> + <nl> + const upb_msgdef * upb_oneofdef_containingtype ( const upb_oneofdef * o ) { <nl> + return o - > parent ; <nl> + } <nl> + <nl> + int upb_oneofdef_numfields ( const upb_oneofdef * o ) { <nl> + return upb_strtable_count ( & o - > ntof ) ; <nl> + } <nl> + <nl> + bool upb_oneofdef_addfield ( upb_oneofdef * o , upb_fielddef * f , <nl> + const void * ref_donor , <nl> + upb_status * s ) { <nl> + assert ( ! upb_oneofdef_isfrozen ( o ) ) ; <nl> + assert ( ! o - > parent | | ! upb_msgdef_isfrozen ( o - > parent ) ) ; <nl> + <nl> + / / This method is idempotent . Check if | f | is already part of this oneofdef <nl> + / / and return immediately if so . <nl> + if ( upb_fielddef_containingoneof ( f ) = = o ) { <nl> + return true ; <nl> + } <nl> + <nl> + / / The field must have an OPTIONAL label . <nl> + if ( upb_fielddef_label ( f ) ! = UPB_LABEL_OPTIONAL ) { <nl> + upb_status_seterrmsg ( s , " fields in oneof must have OPTIONAL label " ) ; <nl> + return false ; <nl> + } <nl> + <nl> + / / Check that no field with this name or number exists already in the oneof . <nl> + / / Also check that the field is not already part of a oneof . <nl> + if ( upb_fielddef_name ( f ) = = NULL | | upb_fielddef_number ( f ) = = 0 ) { <nl> + upb_status_seterrmsg ( s , " field name or number were not set " ) ; <nl> + return false ; <nl> + } else if ( upb_oneofdef_itof ( o , upb_fielddef_number ( f ) ) | | <nl> + upb_oneofdef_ntofz ( o , upb_fielddef_name ( f ) ) ) { <nl> + upb_status_seterrmsg ( s , " duplicate field name or number " ) ; <nl> + return false ; <nl> + } else if ( upb_fielddef_containingoneof ( f ) ! = NULL ) { <nl> + upb_status_seterrmsg ( s , " fielddef already belongs to a oneof " ) ; <nl> + return false ; <nl> + } <nl> + <nl> + / / We allow adding a field to the oneof either if the field is not part of a <nl> + / / msgdef , or if it is and we are also part of the same msgdef . <nl> + if ( o - > parent = = NULL ) { <nl> + / / If we ' re not in a msgdef , the field cannot be either . Otherwise we would <nl> + / / need to magically add this oneof to a msgdef to remain consistent , which <nl> + / / is surprising behavior . <nl> + if ( upb_fielddef_containingtype ( f ) ! = NULL ) { <nl> + upb_status_seterrmsg ( s , " fielddef already belongs to a message , but " <nl> + " oneof does not " ) ; <nl> + return false ; <nl> + } <nl> + } else { <nl> + / / If we ' re in a msgdef , the user can add fields that either aren ' t in any <nl> + / / msgdef ( in which case they ' re added to our msgdef ) or already a part of <nl> + / / our msgdef . <nl> + if ( upb_fielddef_containingtype ( f ) ! = NULL & & <nl> + upb_fielddef_containingtype ( f ) ! = o - > parent ) { <nl> + upb_status_seterrmsg ( s , " fielddef belongs to a different message " <nl> + " than oneof " ) ; <nl> + return false ; <nl> + } <nl> + } <nl> + <nl> + / / Commit phase . First add the field to our parent msgdef , if any , because <nl> + / / that may fail ; then add the field to our own tables . <nl> + <nl> + if ( o - > parent ! = NULL & & upb_fielddef_containingtype ( f ) = = NULL ) { <nl> + if ( ! upb_msgdef_addfield ( ( upb_msgdef * ) o - > parent , f , NULL , s ) ) { <nl> + return false ; <nl> + } <nl> + } <nl> + <nl> + release_containingtype ( f ) ; <nl> + f - > oneof = o ; <nl> + upb_inttable_insert ( & o - > itof , upb_fielddef_number ( f ) , upb_value_ptr ( f ) ) ; <nl> + upb_strtable_insert ( & o - > ntof , upb_fielddef_name ( f ) , upb_value_ptr ( f ) ) ; <nl> + upb_ref2 ( f , o ) ; <nl> + upb_ref2 ( o , f ) ; <nl> + if ( ref_donor ) upb_fielddef_unref ( f , ref_donor ) ; <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + const upb_fielddef * upb_oneofdef_ntof ( const upb_oneofdef * o , <nl> + const char * name , size_t length ) { <nl> + upb_value val ; <nl> + return upb_strtable_lookup2 ( & o - > ntof , name , length , & val ) ? <nl> + upb_value_getptr ( val ) : NULL ; <nl> + } <nl> + <nl> + const upb_fielddef * upb_oneofdef_itof ( const upb_oneofdef * o , uint32_t num ) { <nl> + upb_value val ; <nl> + return upb_inttable_lookup32 ( & o - > itof , num , & val ) ? <nl> + upb_value_getptr ( val ) : NULL ; <nl> + } <nl> + <nl> + void upb_oneof_begin ( upb_oneof_iter * iter , const upb_oneofdef * o ) { <nl> + upb_inttable_begin ( iter , & o - > itof ) ; <nl> + } <nl> + <nl> + void upb_oneof_next ( upb_oneof_iter * iter ) { <nl> + upb_inttable_next ( iter ) ; <nl> + } <nl> + <nl> + bool upb_oneof_done ( upb_oneof_iter * iter ) { <nl> + return upb_inttable_done ( iter ) ; <nl> + } <nl> + <nl> + upb_fielddef * upb_oneof_iter_field ( const upb_oneof_iter * iter ) { <nl> + return ( upb_fielddef * ) upb_value_getptr ( upb_inttable_iter_value ( iter ) ) ; <nl> + } <nl> + <nl> + void upb_oneof_iter_setdone ( upb_oneof_iter * iter ) { <nl> upb_inttable_iter_setdone ( iter ) ; <nl> } <nl> / * <nl> static void freehandlers ( upb_refcounted * r ) { <nl> static void visithandlers ( const upb_refcounted * r , upb_refcounted_visit * visit , <nl> void * closure ) { <nl> const upb_handlers * h = ( const upb_handlers * ) r ; <nl> - upb_msg_iter i ; <nl> - for ( upb_msg_begin ( & i , h - > msg ) ; ! upb_msg_done ( & i ) ; upb_msg_next ( & i ) ) { <nl> + upb_msg_field_iter i ; <nl> + for ( upb_msg_field_begin ( & i , h - > msg ) ; <nl> + ! upb_msg_field_done ( & i ) ; <nl> + upb_msg_field_next ( & i ) ) { <nl> upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> if ( ! upb_fielddef_issubmsg ( f ) ) continue ; <nl> const upb_handlers * sub = upb_handlers_getsubhandlers ( h , f ) ; <nl> static upb_handlers * newformsg ( const upb_msgdef * m , const void * owner , <nl> <nl> / / For each submessage field , get or create a handlers object and set it as <nl> / / the subhandlers . <nl> - upb_msg_iter i ; <nl> - for ( upb_msg_begin ( & i , m ) ; ! upb_msg_done ( & i ) ; upb_msg_next ( & i ) ) { <nl> + upb_msg_field_iter i ; <nl> + for ( upb_msg_field_begin ( & i , m ) ; <nl> + ! upb_msg_field_done ( & i ) ; <nl> + upb_msg_field_next ( & i ) ) { <nl> upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> if ( ! upb_fielddef_issubmsg ( f ) ) continue ; <nl> <nl> bool upb_handlers_freeze ( upb_handlers * const * handlers , int n , upb_status * s ) { <nl> <nl> / / Check that there are no closure mismatches due to missing Start * handlers <nl> / / or subhandlers with different type - level types . <nl> - upb_msg_iter j ; <nl> - for ( upb_msg_begin ( & j , h - > msg ) ; ! upb_msg_done ( & j ) ; upb_msg_next ( & j ) ) { <nl> + upb_msg_field_iter j ; <nl> + for ( upb_msg_field_begin ( & j , h - > msg ) ; <nl> + ! upb_msg_field_done ( & j ) ; <nl> + upb_msg_field_next ( & j ) ) { <nl> <nl> const upb_fielddef * f = upb_msg_iter_field ( & j ) ; <nl> if ( upb_fielddef_isseq ( f ) ) { <nl> static bool upb_resolve_dfs ( const upb_def * def , upb_strtable * addtab , <nl> / / For messages , continue the recursion by visiting all subdefs . <nl> const upb_msgdef * m = upb_dyncast_msgdef ( def ) ; <nl> if ( m ) { <nl> - upb_msg_iter i ; <nl> - for ( upb_msg_begin ( & i , m ) ; ! upb_msg_done ( & i ) ; upb_msg_next ( & i ) ) { <nl> + upb_msg_field_iter i ; <nl> + for ( upb_msg_field_begin ( & i , m ) ; <nl> + ! upb_msg_field_done ( & i ) ; <nl> + upb_msg_field_next ( & i ) ) { <nl> upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> if ( ! upb_fielddef_hassubdef ( f ) ) continue ; <nl> / / | = to avoid short - circuit ; we need its side - effects . <nl> bool upb_symtab_add ( upb_symtab * s , upb_def * const * defs , int n , void * ref_donor , <nl> / / Type names are resolved relative to the message in which they appear . <nl> const char * base = upb_msgdef_fullname ( m ) ; <nl> <nl> - upb_msg_iter j ; <nl> - for ( upb_msg_begin ( & j , m ) ; ! upb_msg_done ( & j ) ; upb_msg_next ( & j ) ) { <nl> + upb_msg_field_iter j ; <nl> + for ( upb_msg_field_begin ( & j , m ) ; <nl> + ! upb_msg_field_done ( & j ) ; <nl> + upb_msg_field_next ( & j ) ) { <nl> upb_fielddef * f = upb_msg_iter_field ( & j ) ; <nl> const char * name = upb_fielddef_subdefname ( f ) ; <nl> if ( name & & ! upb_fielddef_subdef ( f ) ) { <nl> char * upb_strdup ( const char * s ) { <nl> } <nl> <nl> char * upb_strdup2 ( const char * s , size_t len ) { <nl> - / / Prevent overflow errors . <nl> - if ( len = = SIZE_MAX ) return NULL ; <nl> / / Always null - terminate , even if binary data ; but don ' t rely on the input to <nl> / / have a null - terminating byte since it may be a raw binary buffer . <nl> size_t n = len + 1 ; <nl> char * p = malloc ( n ) ; <nl> - if ( p ) { <nl> - memcpy ( p , s , len ) ; <nl> - p [ len ] = 0 ; <nl> - } <nl> + if ( p ) memcpy ( p , s , len ) ; <nl> + p [ len ] = 0 ; <nl> return p ; <nl> } <nl> <nl> static void compile_method ( compiler * c , upb_pbdecodermethod * method ) { <nl> putsel ( c , OP_STARTMSG , UPB_STARTMSG_SELECTOR , h ) ; <nl> label ( c , LABEL_FIELD ) ; <nl> uint32_t * start_pc = c - > pc ; <nl> - upb_msg_iter i ; <nl> - for ( upb_msg_begin ( & i , md ) ; ! upb_msg_done ( & i ) ; upb_msg_next ( & i ) ) { <nl> + upb_msg_field_iter i ; <nl> + for ( upb_msg_field_begin ( & i , md ) ; <nl> + ! upb_msg_field_done ( & i ) ; <nl> + upb_msg_field_next ( & i ) ) { <nl> const upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> upb_fieldtype_t type = upb_fielddef_type ( f ) ; <nl> <nl> static void find_methods ( compiler * c , const upb_handlers * h ) { <nl> newmethod ( h , c - > group ) ; <nl> <nl> / / Find submethods . <nl> - upb_msg_iter i ; <nl> + upb_msg_field_iter i ; <nl> const upb_msgdef * md = upb_handlers_msgdef ( h ) ; <nl> - for ( upb_msg_begin ( & i , md ) ; ! upb_msg_done ( & i ) ; upb_msg_next ( & i ) ) { <nl> + for ( upb_msg_field_begin ( & i , md ) ; <nl> + ! upb_msg_field_done ( & i ) ; <nl> + upb_msg_field_next ( & i ) ) { <nl> const upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> const upb_handlers * sub_h ; <nl> if ( upb_fielddef_type ( f ) = = UPB_TYPE_MESSAGE & & <nl> static void set_bytecode_handlers ( mgroup * g ) { <nl> } <nl> <nl> <nl> - / * JIT setup . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * JIT setup . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> # ifdef UPB_USE_JIT_X64 <nl> <nl> static void newhandlers_callback ( const void * closure , upb_handlers * h ) { <nl> upb_handlers_setendmsg ( h , endmsg , NULL ) ; <nl> <nl> const upb_msgdef * m = upb_handlers_msgdef ( h ) ; <nl> - upb_msg_iter i ; <nl> - for ( upb_msg_begin ( & i , m ) ; ! upb_msg_done ( & i ) ; upb_msg_next ( & i ) ) { <nl> + upb_msg_field_iter i ; <nl> + for ( upb_msg_field_begin ( & i , m ) ; <nl> + ! upb_msg_field_done ( & i ) ; <nl> + upb_msg_field_next ( & i ) ) { <nl> const upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> bool packed = upb_fielddef_isseq ( f ) & & upb_fielddef_isprimitive ( f ) & & <nl> upb_fielddef_packed ( f ) ; <nl> static void onmreg ( const void * c , upb_handlers * h ) { <nl> upb_handlers_setstartmsg ( h , textprinter_startmsg , NULL ) ; <nl> upb_handlers_setendmsg ( h , textprinter_endmsg , NULL ) ; <nl> <nl> - upb_msg_iter i ; <nl> - for ( upb_msg_begin ( & i , m ) ; ! upb_msg_done ( & i ) ; upb_msg_next ( & i ) ) { <nl> + upb_msg_field_iter i ; <nl> + for ( upb_msg_field_begin ( & i , m ) ; <nl> + ! upb_msg_field_done ( & i ) ; <nl> + upb_msg_field_next ( & i ) ) { <nl> upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER ; <nl> upb_handlerattr_sethandlerdata ( & attr , f ) ; <nl> static bool base64_push ( upb_json_parser * p , upb_selector_t sel , const char * ptr , <nl> / / the true value in a contiguous buffer . <nl> <nl> static void assert_accumulate_empty ( upb_json_parser * p ) { <nl> + UPB_UNUSED ( p ) ; <nl> assert ( p - > accumulated = = NULL ) ; <nl> assert ( p - > accumulated_len = = 0 ) ; <nl> } <nl> static void end_object ( upb_json_parser * p ) { <nl> / / final state once , when the closing ' " ' is seen . <nl> <nl> <nl> - # line 904 " upb / json / parser . rl " <nl> + # line 905 " upb / json / parser . rl " <nl> <nl> <nl> <nl> - # line 816 " upb / json / parser . c " <nl> + # line 817 " upb / json / parser . c " <nl> static const char _json_actions [ ] = { <nl> 0 , 1 , 0 , 1 , 2 , 1 , 3 , 1 , <nl> 5 , 1 , 6 , 1 , 7 , 1 , 8 , 1 , <nl> static const int json_en_value_machine = 27 ; <nl> static const int json_en_main = 1 ; <nl> <nl> <nl> - # line 907 " upb / json / parser . rl " <nl> + # line 908 " upb / json / parser . rl " <nl> <nl> size_t parse ( void * closure , const void * hd , const char * buf , size_t size , <nl> const upb_bufhandle * handle ) { <nl> size_t parse ( void * closure , const void * hd , const char * buf , size_t size , <nl> capture_resume ( parser , buf ) ; <nl> <nl> <nl> - # line 987 " upb / json / parser . c " <nl> + # line 988 " upb / json / parser . c " <nl> { <nl> int _klen ; <nl> unsigned int _trans ; <nl> size_t parse ( void * closure , const void * hd , const char * buf , size_t size , <nl> switch ( * _acts + + ) <nl> { <nl> case 0 : <nl> - # line 819 " upb / json / parser . rl " <nl> + # line 820 " upb / json / parser . rl " <nl> { p - - ; { cs = stack [ - - top ] ; goto _again ; } } <nl> break ; <nl> case 1 : <nl> - # line 820 " upb / json / parser . rl " <nl> + # line 821 " upb / json / parser . rl " <nl> { p - - ; { stack [ top + + ] = cs ; cs = 10 ; goto _again ; } } <nl> break ; <nl> case 2 : <nl> - # line 824 " upb / json / parser . rl " <nl> + # line 825 " upb / json / parser . rl " <nl> { start_text ( parser , p ) ; } <nl> break ; <nl> case 3 : <nl> - # line 825 " upb / json / parser . rl " <nl> + # line 826 " upb / json / parser . rl " <nl> { CHECK_RETURN_TOP ( end_text ( parser , p ) ) ; } <nl> break ; <nl> case 4 : <nl> - # line 831 " upb / json / parser . rl " <nl> + # line 832 " upb / json / parser . rl " <nl> { start_hex ( parser ) ; } <nl> break ; <nl> case 5 : <nl> - # line 832 " upb / json / parser . rl " <nl> + # line 833 " upb / json / parser . rl " <nl> { hexdigit ( parser , p ) ; } <nl> break ; <nl> case 6 : <nl> - # line 833 " upb / json / parser . rl " <nl> + # line 834 " upb / json / parser . rl " <nl> { CHECK_RETURN_TOP ( end_hex ( parser ) ) ; } <nl> break ; <nl> case 7 : <nl> - # line 839 " upb / json / parser . rl " <nl> + # line 840 " upb / json / parser . rl " <nl> { CHECK_RETURN_TOP ( escape ( parser , p ) ) ; } <nl> break ; <nl> case 8 : <nl> - # line 845 " upb / json / parser . rl " <nl> + # line 846 " upb / json / parser . rl " <nl> { p - - ; { cs = stack [ - - top ] ; goto _again ; } } <nl> break ; <nl> case 9 : <nl> - # line 848 " upb / json / parser . rl " <nl> + # line 849 " upb / json / parser . rl " <nl> { { stack [ top + + ] = cs ; cs = 19 ; goto _again ; } } <nl> break ; <nl> case 10 : <nl> - # line 850 " upb / json / parser . rl " <nl> + # line 851 " upb / json / parser . rl " <nl> { p - - ; { stack [ top + + ] = cs ; cs = 27 ; goto _again ; } } <nl> break ; <nl> case 11 : <nl> - # line 855 " upb / json / parser . rl " <nl> + # line 856 " upb / json / parser . rl " <nl> { start_member ( parser ) ; } <nl> break ; <nl> case 12 : <nl> - # line 856 " upb / json / parser . rl " <nl> + # line 857 " upb / json / parser . rl " <nl> { CHECK_RETURN_TOP ( end_member ( parser ) ) ; } <nl> break ; <nl> case 13 : <nl> - # line 859 " upb / json / parser . rl " <nl> + # line 860 " upb / json / parser . rl " <nl> { clear_member ( parser ) ; } <nl> break ; <nl> case 14 : <nl> - # line 865 " upb / json / parser . rl " <nl> + # line 866 " upb / json / parser . rl " <nl> { start_object ( parser ) ; } <nl> break ; <nl> case 15 : <nl> - # line 868 " upb / json / parser . rl " <nl> + # line 869 " upb / json / parser . rl " <nl> { end_object ( parser ) ; } <nl> break ; <nl> case 16 : <nl> - # line 874 " upb / json / parser . rl " <nl> + # line 875 " upb / json / parser . rl " <nl> { CHECK_RETURN_TOP ( start_array ( parser ) ) ; } <nl> break ; <nl> case 17 : <nl> - # line 878 " upb / json / parser . rl " <nl> + # line 879 " upb / json / parser . rl " <nl> { end_array ( parser ) ; } <nl> break ; <nl> case 18 : <nl> - # line 883 " upb / json / parser . rl " <nl> + # line 884 " upb / json / parser . rl " <nl> { start_number ( parser , p ) ; } <nl> break ; <nl> case 19 : <nl> - # line 884 " upb / json / parser . rl " <nl> + # line 885 " upb / json / parser . rl " <nl> { CHECK_RETURN_TOP ( end_number ( parser , p ) ) ; } <nl> break ; <nl> case 20 : <nl> - # line 886 " upb / json / parser . rl " <nl> + # line 887 " upb / json / parser . rl " <nl> { CHECK_RETURN_TOP ( start_stringval ( parser ) ) ; } <nl> break ; <nl> case 21 : <nl> - # line 887 " upb / json / parser . rl " <nl> + # line 888 " upb / json / parser . rl " <nl> { CHECK_RETURN_TOP ( end_stringval ( parser ) ) ; } <nl> break ; <nl> case 22 : <nl> - # line 889 " upb / json / parser . rl " <nl> + # line 890 " upb / json / parser . rl " <nl> { CHECK_RETURN_TOP ( parser_putbool ( parser , true ) ) ; } <nl> break ; <nl> case 23 : <nl> - # line 891 " upb / json / parser . rl " <nl> + # line 892 " upb / json / parser . rl " <nl> { CHECK_RETURN_TOP ( parser_putbool ( parser , false ) ) ; } <nl> break ; <nl> case 24 : <nl> - # line 893 " upb / json / parser . rl " <nl> + # line 894 " upb / json / parser . rl " <nl> { / * null value * / } <nl> break ; <nl> case 25 : <nl> - # line 895 " upb / json / parser . rl " <nl> + # line 896 " upb / json / parser . rl " <nl> { CHECK_RETURN_TOP ( start_subobject ( parser ) ) ; } <nl> break ; <nl> case 26 : <nl> - # line 896 " upb / json / parser . rl " <nl> + # line 897 " upb / json / parser . rl " <nl> { end_subobject ( parser ) ; } <nl> break ; <nl> case 27 : <nl> - # line 901 " upb / json / parser . rl " <nl> + # line 902 " upb / json / parser . rl " <nl> { p - - ; { cs = stack [ - - top ] ; goto _again ; } } <nl> break ; <nl> - # line 1173 " upb / json / parser . c " <nl> + # line 1174 " upb / json / parser . c " <nl> } <nl> } <nl> <nl> size_t parse ( void * closure , const void * hd , const char * buf , size_t size , <nl> _out : { } <nl> } <nl> <nl> - # line 926 " upb / json / parser . rl " <nl> + # line 927 " upb / json / parser . rl " <nl> <nl> if ( p ! = pe ) { <nl> upb_status_seterrf ( parser - > status , " Parse error at % s \ n " , p ) ; <nl> void upb_json_parser_reset ( upb_json_parser * p ) { <nl> int top ; <nl> / / Emit Ragel initialization of the parser . <nl> <nl> - # line 1235 " upb / json / parser . c " <nl> + # line 1236 " upb / json / parser . c " <nl> { <nl> cs = json_start ; <nl> top = 0 ; <nl> } <nl> <nl> - # line 974 " upb / json / parser . rl " <nl> + # line 975 " upb / json / parser . rl " <nl> p - > current_state = cs ; <nl> p - > parser_top = top ; <nl> accumulate_clear ( p ) ; <nl> void printer_sethandlers ( const void * closure , upb_handlers * h ) { <nl> } \ <nl> break ; <nl> <nl> - upb_msg_iter i ; <nl> - upb_msg_begin ( & i , upb_handlers_msgdef ( h ) ) ; <nl> - for ( ; ! upb_msg_done ( & i ) ; upb_msg_next ( & i ) ) { <nl> + upb_msg_field_iter i ; <nl> + upb_msg_field_begin ( & i , upb_handlers_msgdef ( h ) ) ; <nl> + for ( ; ! upb_msg_field_done ( & i ) ; upb_msg_field_next ( & i ) ) { <nl> const upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> <nl> upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER ; <nl> mmm a / ruby / ext / google / protobuf_c / upb . h <nl> ppp b / ruby / ext / google / protobuf_c / upb . h <nl> typedef struct { <nl> # define UPB_STRTABLE_INIT ( count , mask , ctype , size_lg2 , entries ) \ <nl> { { count , mask , ctype , size_lg2 , entries } } <nl> <nl> + # define UPB_EMPTY_STRTABLE_INIT ( ctype ) \ <nl> + UPB_STRTABLE_INIT ( 0 , 0 , ctype , 0 , NULL ) <nl> + <nl> typedef struct { <nl> upb_table t ; / / For entries that don ' t fit in the array part . <nl> const _upb_value * array ; / / Array part of the table . See const note above . <nl> class Def ; <nl> class EnumDef ; <nl> class FieldDef ; <nl> class MessageDef ; <nl> + class OneofDef ; <nl> } <nl> # endif <nl> <nl> UPB_DECLARE_TYPE ( upb : : Def , upb_def ) ; <nl> UPB_DECLARE_TYPE ( upb : : EnumDef , upb_enumdef ) ; <nl> UPB_DECLARE_TYPE ( upb : : FieldDef , upb_fielddef ) ; <nl> UPB_DECLARE_TYPE ( upb : : MessageDef , upb_msgdef ) ; <nl> + UPB_DECLARE_TYPE ( upb : : OneofDef , upb_oneofdef ) ; <nl> <nl> / / Maximum field number allowed for FieldDefs . This is an inherent limit of the <nl> / / protobuf wire format . <nl> typedef enum { <nl> UPB_DEF_MSG , <nl> UPB_DEF_FIELD , <nl> UPB_DEF_ENUM , <nl> + UPB_DEF_ONEOF , <nl> UPB_DEF_SERVICE , / / Not yet implemented . <nl> UPB_DEF_ANY = - 1 , / / Wildcard for upb_symtab_get * ( ) <nl> } upb_deftype_t ; <nl> UPB_DEFINE_DEF ( upb : : FieldDef , fielddef , FIELD , <nl> const MessageDef * containing_type ( ) const ; <nl> const char * containing_type_name ( ) ; <nl> <nl> + / / The OneofDef to which this field belongs , or NULL if this field is not part <nl> + / / of a oneof . <nl> + const OneofDef * containing_oneof ( ) const ; <nl> + <nl> / / The field ' s type according to the enum in descriptor . proto . This is not <nl> / / the same as UPB_TYPE_ * , because it distinguishes between ( for example ) <nl> / / INT32 and SINT32 , whereas our " type " enum does not . This return of <nl> UPB_DEFINE_STRUCT ( upb_fielddef , upb_def , <nl> } sub ; / / The msgdef or enumdef for this field , if upb_hassubdef ( f ) . <nl> bool subdef_is_symbolic ; <nl> bool msg_is_symbolic ; <nl> + const upb_oneofdef * oneof ; <nl> bool default_is_string ; <nl> bool type_is_set_ ; / / False until type is explicitly set . <nl> bool is_extension_ ; <nl> UPB_DEFINE_STRUCT ( upb_fielddef , upb_def , <nl> ) ) ; <nl> <nl> # define UPB_FIELDDEF_INIT ( label , type , intfmt , tagdelim , is_extension , lazy , \ <nl> - packed , name , num , msgdef , subdef , selector_base , \ <nl> + packed , name , num , msgdef , subdef , selector_base , \ <nl> index , defaultval , refs , ref2s ) \ <nl> { \ <nl> UPB_DEF_INIT ( name , UPB_DEF_FIELD , refs , ref2s ) , defaultval , { msgdef } , \ <nl> - { subdef } , false , false , \ <nl> + { subdef } , NULL , false , false , \ <nl> type = = UPB_TYPE_STRING | | type = = UPB_TYPE_BYTES , true , is_extension , \ <nl> lazy , packed , intfmt , tagdelim , type , label , num , selector_base , index \ <nl> } <nl> bool upb_fielddef_isextension ( const upb_fielddef * f ) ; <nl> bool upb_fielddef_lazy ( const upb_fielddef * f ) ; <nl> bool upb_fielddef_packed ( const upb_fielddef * f ) ; <nl> const upb_msgdef * upb_fielddef_containingtype ( const upb_fielddef * f ) ; <nl> + const upb_oneofdef * upb_fielddef_containingoneof ( const upb_fielddef * f ) ; <nl> upb_msgdef * upb_fielddef_containingtype_mutable ( upb_fielddef * f ) ; <nl> const char * upb_fielddef_containingtypename ( upb_fielddef * f ) ; <nl> upb_intfmt_t upb_fielddef_intfmt ( const upb_fielddef * f ) ; <nl> UPB_END_EXTERN_C / / } <nl> <nl> / * upb : : MessageDef * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> - typedef upb_inttable_iter upb_msg_iter ; <nl> + typedef upb_inttable_iter upb_msg_field_iter ; <nl> + typedef upb_strtable_iter upb_msg_oneof_iter ; <nl> <nl> / / Structure that describes a single . proto message type . <nl> / / <nl> UPB_DEFINE_DEF ( upb : : MessageDef , msgdef , MSG , UPB_QUOTE ( <nl> / / The number of fields that belong to the MessageDef . <nl> int field_count ( ) const ; <nl> <nl> + / / The number of oneofs that belong to the MessageDef . <nl> + int oneof_count ( ) const ; <nl> + <nl> / / Adds a field ( upb_fielddef object ) to a msgdef . Requires that the msgdef <nl> / / and the fielddefs are mutable . The fielddef ' s name and number must be <nl> / / set , and the message may not already contain any field with this name or <nl> / / number , and this fielddef may not be part of another message . In error <nl> / / cases false is returned and the msgdef is unchanged . <nl> + / / <nl> + / / If the given field is part of a oneof , this call succeeds if and only if <nl> + / / that oneof is already part of this msgdef . ( Note that adding a oneof to a <nl> + / / msgdef automatically adds all of its fields to the msgdef at the time that <nl> + / / the oneof is added , so it is usually more idiomatic to add the oneof ' s <nl> + / / fields first then add the oneof to the msgdef . This case is supported for <nl> + / / convenience . ) <nl> + / / <nl> + / / If | f | is already part of this MessageDef , this method performs no action <nl> + / / and returns true ( success ) . Thus , this method is idempotent . <nl> bool AddField ( FieldDef * f , Status * s ) ; <nl> bool AddField ( const reffed_ptr < FieldDef > & f , Status * s ) ; <nl> <nl> + / / Adds a oneof ( upb_oneofdef object ) to a msgdef . Requires that the msgdef , <nl> + / / oneof , and any fielddefs are mutable , that the fielddefs contained in the <nl> + / / oneof do not have any name or number conflicts with existing fields in the <nl> + / / msgdef , and that the oneof ' s name is unique among all oneofs in the msgdef . <nl> + / / If the oneof is added successfully , all of its fields will be added <nl> + / / directly to the msgdef as well . In error cases , false is returned and the <nl> + / / msgdef is unchanged . <nl> + bool AddOneof ( OneofDef * o , Status * s ) ; <nl> + bool AddOneof ( const reffed_ptr < OneofDef > & o , Status * s ) ; <nl> + <nl> / / These return NULL if the field is not found . <nl> FieldDef * FindFieldByNumber ( uint32_t number ) ; <nl> FieldDef * FindFieldByName ( const char * name , size_t len ) ; <nl> UPB_DEFINE_DEF ( upb : : MessageDef , msgdef , MSG , UPB_QUOTE ( <nl> return FindFieldByName ( str . c_str ( ) , str . size ( ) ) ; <nl> } <nl> <nl> + OneofDef * FindOneofByName ( const char * name , size_t len ) ; <nl> + const OneofDef * FindOneofByName ( const char * name , size_t len ) const ; <nl> + <nl> + OneofDef * FindOneofByName ( const char * name ) { <nl> + return FindOneofByName ( name , strlen ( name ) ) ; <nl> + } <nl> + const OneofDef * FindOneofByName ( const char * name ) const { <nl> + return FindOneofByName ( name , strlen ( name ) ) ; <nl> + } <nl> + <nl> + template < class T > <nl> + OneofDef * FindOneofByName ( const T & str ) { <nl> + return FindOneofByName ( str . c_str ( ) , str . size ( ) ) ; <nl> + } <nl> + template < class T > <nl> + const OneofDef * FindOneofByName ( const T & str ) const { <nl> + return FindOneofByName ( str . c_str ( ) , str . size ( ) ) ; <nl> + } <nl> + <nl> / / Returns a new msgdef that is a copy of the given msgdef ( and a copy of all <nl> / / the fields ) but with any references to submessages broken and replaced <nl> / / with just the name of the submessage . Returns NULL if memory allocation <nl> UPB_DEFINE_DEF ( upb : : MessageDef , msgdef , MSG , UPB_QUOTE ( <nl> bool mapentry ( ) const ; <nl> <nl> / / Iteration over fields . The order is undefined . <nl> - class iterator : public std : : iterator < std : : forward_iterator_tag , FieldDef * > { <nl> + class field_iterator <nl> + : public std : : iterator < std : : forward_iterator_tag , FieldDef * > { <nl> public : <nl> - explicit iterator ( MessageDef * md ) ; <nl> - static iterator end ( MessageDef * md ) ; <nl> + explicit field_iterator ( MessageDef * md ) ; <nl> + static field_iterator end ( MessageDef * md ) ; <nl> <nl> void operator + + ( ) ; <nl> FieldDef * operator * ( ) const ; <nl> - bool operator ! = ( const iterator & other ) const ; <nl> - bool operator = = ( const iterator & other ) const ; <nl> + bool operator ! = ( const field_iterator & other ) const ; <nl> + bool operator = = ( const field_iterator & other ) const ; <nl> <nl> private : <nl> - upb_msg_iter iter_ ; <nl> + upb_msg_field_iter iter_ ; <nl> } ; <nl> <nl> - class const_iterator <nl> + class const_field_iterator <nl> : public std : : iterator < std : : forward_iterator_tag , const FieldDef * > { <nl> public : <nl> - explicit const_iterator ( const MessageDef * md ) ; <nl> - static const_iterator end ( const MessageDef * md ) ; <nl> + explicit const_field_iterator ( const MessageDef * md ) ; <nl> + static const_field_iterator end ( const MessageDef * md ) ; <nl> <nl> void operator + + ( ) ; <nl> const FieldDef * operator * ( ) const ; <nl> - bool operator ! = ( const const_iterator & other ) const ; <nl> - bool operator = = ( const const_iterator & other ) const ; <nl> + bool operator ! = ( const const_field_iterator & other ) const ; <nl> + bool operator = = ( const const_field_iterator & other ) const ; <nl> <nl> private : <nl> - upb_msg_iter iter_ ; <nl> + upb_msg_field_iter iter_ ; <nl> } ; <nl> <nl> - iterator begin ( ) ; <nl> - iterator end ( ) ; <nl> - const_iterator begin ( ) const ; <nl> - const_iterator end ( ) const ; <nl> + / / Iteration over oneofs . The order is undefined . <nl> + class oneof_iterator <nl> + : public std : : iterator < std : : forward_iterator_tag , FieldDef * > { <nl> + public : <nl> + explicit oneof_iterator ( MessageDef * md ) ; <nl> + static oneof_iterator end ( MessageDef * md ) ; <nl> + <nl> + void operator + + ( ) ; <nl> + OneofDef * operator * ( ) const ; <nl> + bool operator ! = ( const oneof_iterator & other ) const ; <nl> + bool operator = = ( const oneof_iterator & other ) const ; <nl> + <nl> + private : <nl> + upb_msg_oneof_iter iter_ ; <nl> + } ; <nl> + <nl> + class const_oneof_iterator <nl> + : public std : : iterator < std : : forward_iterator_tag , const FieldDef * > { <nl> + public : <nl> + explicit const_oneof_iterator ( const MessageDef * md ) ; <nl> + static const_oneof_iterator end ( const MessageDef * md ) ; <nl> + <nl> + void operator + + ( ) ; <nl> + const OneofDef * operator * ( ) const ; <nl> + bool operator ! = ( const const_oneof_iterator & other ) const ; <nl> + bool operator = = ( const const_oneof_iterator & other ) const ; <nl> + <nl> + private : <nl> + upb_msg_oneof_iter iter_ ; <nl> + } ; <nl> + <nl> + class FieldAccessor { <nl> + public : <nl> + explicit FieldAccessor ( MessageDef * msg ) : msg_ ( msg ) { } <nl> + field_iterator begin ( ) { return msg_ - > field_begin ( ) ; } <nl> + field_iterator end ( ) { return msg_ - > field_end ( ) ; } <nl> + private : <nl> + MessageDef * msg_ ; <nl> + } ; <nl> + <nl> + class ConstFieldAccessor { <nl> + public : <nl> + explicit ConstFieldAccessor ( const MessageDef * msg ) : msg_ ( msg ) { } <nl> + const_field_iterator begin ( ) { return msg_ - > field_begin ( ) ; } <nl> + const_field_iterator end ( ) { return msg_ - > field_end ( ) ; } <nl> + private : <nl> + const MessageDef * msg_ ; <nl> + } ; <nl> + <nl> + class OneofAccessor { <nl> + public : <nl> + explicit OneofAccessor ( MessageDef * msg ) : msg_ ( msg ) { } <nl> + oneof_iterator begin ( ) { return msg_ - > oneof_begin ( ) ; } <nl> + oneof_iterator end ( ) { return msg_ - > oneof_end ( ) ; } <nl> + private : <nl> + MessageDef * msg_ ; <nl> + } ; <nl> + <nl> + class ConstOneofAccessor { <nl> + public : <nl> + explicit ConstOneofAccessor ( const MessageDef * msg ) : msg_ ( msg ) { } <nl> + const_oneof_iterator begin ( ) { return msg_ - > oneof_begin ( ) ; } <nl> + const_oneof_iterator end ( ) { return msg_ - > oneof_end ( ) ; } <nl> + private : <nl> + const MessageDef * msg_ ; <nl> + } ; <nl> + <nl> + field_iterator field_begin ( ) ; <nl> + field_iterator field_end ( ) ; <nl> + const_field_iterator field_begin ( ) const ; <nl> + const_field_iterator field_end ( ) const ; <nl> + <nl> + oneof_iterator oneof_begin ( ) ; <nl> + oneof_iterator oneof_end ( ) ; <nl> + const_oneof_iterator oneof_begin ( ) const ; <nl> + const_oneof_iterator oneof_end ( ) const ; <nl> + <nl> + FieldAccessor fields ( ) { return FieldAccessor ( this ) ; } <nl> + ConstFieldAccessor fields ( ) const { return ConstFieldAccessor ( this ) ; } <nl> + OneofAccessor oneofs ( ) { return OneofAccessor ( this ) ; } <nl> + ConstOneofAccessor oneofs ( ) const { return ConstOneofAccessor ( this ) ; } <nl> <nl> private : <nl> UPB_DISALLOW_POD_OPS ( MessageDef , upb : : MessageDef ) ; <nl> UPB_DEFINE_STRUCT ( upb_msgdef , upb_def , <nl> upb_inttable itof ; / / int to field <nl> upb_strtable ntof ; / / name to field <nl> <nl> + / / Tables for looking up oneofs by name . <nl> + upb_strtable ntoo ; / / name to oneof <nl> + <nl> / / Is this a map - entry message ? <nl> / / TODO : set this flag properly for static descriptors ; regenerate <nl> / / descriptor . upb . c . <nl> UPB_DEFINE_STRUCT ( upb_msgdef , upb_def , <nl> / / TODO ( haberman ) : proper extension ranges ( there can be multiple ) . <nl> ) ) ; <nl> <nl> + / / TODO : also support static initialization of the oneofs table . This will be <nl> + / / needed if we compile in descriptors that contain oneofs . <nl> # define UPB_MSGDEF_INIT ( name , selector_count , submsg_field_count , itof , ntof , \ <nl> refs , ref2s ) \ <nl> { \ <nl> UPB_DEF_INIT ( name , UPB_DEF_MSG , refs , ref2s ) , selector_count , \ <nl> - submsg_field_count , itof , ntof , false \ <nl> + submsg_field_count , itof , ntof , \ <nl> + UPB_EMPTY_STRTABLE_INIT ( UPB_CTYPE_PTR ) , false \ <nl> } <nl> <nl> UPB_BEGIN_EXTERN_C / / { <nl> bool upb_msgdef_setfullname ( upb_msgdef * m , const char * fullname , upb_status * s ) ; <nl> upb_msgdef * upb_msgdef_dup ( const upb_msgdef * m , const void * owner ) ; <nl> bool upb_msgdef_addfield ( upb_msgdef * m , upb_fielddef * f , const void * ref_donor , <nl> upb_status * s ) ; <nl> + bool upb_msgdef_addoneof ( upb_msgdef * m , upb_oneofdef * o , const void * ref_donor , <nl> + upb_status * s ) ; <nl> <nl> / / Field lookup in a couple of different variations : <nl> / / - itof = int to field <nl> UPB_INLINE upb_fielddef * upb_msgdef_ntof_mutable ( upb_msgdef * m , <nl> return ( upb_fielddef * ) upb_msgdef_ntof ( m , name , len ) ; <nl> } <nl> <nl> + / / Oneof lookup : <nl> + / / - ntoo = name to oneof <nl> + / / - ntooz = name to oneof , null - terminated string . <nl> + const upb_oneofdef * upb_msgdef_ntoo ( const upb_msgdef * m , const char * name , <nl> + size_t len ) ; <nl> + int upb_msgdef_numoneofs ( const upb_msgdef * m ) ; <nl> + <nl> + UPB_INLINE const upb_oneofdef * upb_msgdef_ntooz ( const upb_msgdef * m , <nl> + const char * name ) { <nl> + return upb_msgdef_ntoo ( m , name , strlen ( name ) ) ; <nl> + } <nl> + <nl> + UPB_INLINE upb_oneofdef * upb_msgdef_ntoo_mutable ( upb_msgdef * m , <nl> + const char * name , size_t len ) { <nl> + return ( upb_oneofdef * ) upb_msgdef_ntoo ( m , name , len ) ; <nl> + } <nl> + <nl> void upb_msgdef_setmapentry ( upb_msgdef * m , bool map_entry ) ; <nl> bool upb_msgdef_mapentry ( const upb_msgdef * m ) ; <nl> <nl> - / / upb_msg_iter i ; <nl> - / / for ( upb_msg_begin ( & i , m ) ; ! upb_msg_done ( & i ) ; upb_msg_next ( & i ) ) { <nl> + const upb_oneofdef * upb_msgdef_findoneof ( const upb_msgdef * m , <nl> + const char * name ) ; <nl> + int upb_msgdef_numoneofs ( const upb_msgdef * m ) ; <nl> + <nl> + / / upb_msg_field_iter i ; <nl> + / / for ( upb_msg_field_begin ( & i , m ) ; <nl> + / / ! upb_msg_field_done ( & i ) ; <nl> + / / upb_msg_field_next ( & i ) ) { <nl> / / upb_fielddef * f = upb_msg_iter_field ( & i ) ; <nl> / / / / . . . <nl> / / } <nl> bool upb_msgdef_mapentry ( const upb_msgdef * m ) ; <nl> / / For C we don ' t have separate iterators for const and non - const . <nl> / / It is the caller ' s responsibility to cast the upb_fielddef * to <nl> / / const if the upb_msgdef * is const . <nl> - void upb_msg_begin ( upb_msg_iter * iter , const upb_msgdef * m ) ; <nl> - void upb_msg_next ( upb_msg_iter * iter ) ; <nl> - bool upb_msg_done ( const upb_msg_iter * iter ) ; <nl> - upb_fielddef * upb_msg_iter_field ( const upb_msg_iter * iter ) ; <nl> - void upb_msg_iter_setdone ( upb_msg_iter * iter ) ; <nl> + void upb_msg_field_begin ( upb_msg_field_iter * iter , const upb_msgdef * m ) ; <nl> + void upb_msg_field_next ( upb_msg_field_iter * iter ) ; <nl> + bool upb_msg_field_done ( const upb_msg_field_iter * iter ) ; <nl> + upb_fielddef * upb_msg_iter_field ( const upb_msg_field_iter * iter ) ; <nl> + void upb_msg_field_iter_setdone ( upb_msg_field_iter * iter ) ; <nl> + <nl> + / / Similar to above , we also support iterating through the oneofs in a msgdef . <nl> + void upb_msg_oneof_begin ( upb_msg_oneof_iter * iter , const upb_msgdef * m ) ; <nl> + void upb_msg_oneof_next ( upb_msg_oneof_iter * iter ) ; <nl> + bool upb_msg_oneof_done ( const upb_msg_oneof_iter * iter ) ; <nl> + upb_oneofdef * upb_msg_iter_oneof ( const upb_msg_oneof_iter * iter ) ; <nl> + void upb_msg_oneof_iter_setdone ( upb_msg_oneof_iter * iter ) ; <nl> <nl> UPB_END_EXTERN_C / / } <nl> <nl> int32_t upb_enum_iter_number ( upb_enum_iter * iter ) ; <nl> <nl> UPB_END_EXTERN_C / / } <nl> <nl> + / * upb : : OneofDef * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + typedef upb_inttable_iter upb_oneof_iter ; <nl> + <nl> + / / Class that represents a oneof . Its base class is upb : : Def ( convert with <nl> + / / upb : : upcast ( ) ) . <nl> + UPB_DEFINE_DEF ( upb : : OneofDef , oneofdef , ONEOF , UPB_QUOTE ( <nl> + public : <nl> + / / Returns NULL if memory allocation failed . <nl> + static reffed_ptr < OneofDef > New ( ) ; <nl> + <nl> + / / Functionality from upb : : RefCounted . <nl> + bool IsFrozen ( ) const ; <nl> + void Ref ( const void * owner ) const ; <nl> + void Unref ( const void * owner ) const ; <nl> + void DonateRef ( const void * from , const void * to ) const ; <nl> + void CheckRef ( const void * owner ) const ; <nl> + <nl> + / / Functionality from upb : : Def . <nl> + const char * full_name ( ) const ; <nl> + <nl> + / / Returns the MessageDef that owns this OneofDef . <nl> + const MessageDef * containing_type ( ) const ; <nl> + <nl> + / / Returns the name of this oneof . This is the name used to look up the oneof <nl> + / / by name once added to a message def . <nl> + const char * name ( ) const ; <nl> + bool set_name ( const char * name , Status * s ) ; <nl> + <nl> + / / Returns the number of fields currently defined in the oneof . <nl> + int field_count ( ) const ; <nl> + <nl> + / / Adds a field to the oneof . The field must not have been added to any other <nl> + / / oneof or msgdef . If the oneof is not yet part of a msgdef , then when the <nl> + / / oneof is eventually added to a msgdef , all fields added to the oneof will <nl> + / / also be added to the msgdef at that time . If the oneof is already part of a <nl> + / / msgdef , the field must either be a part of that msgdef already , or must not <nl> + / / be a part of any msgdef ; in the latter case , the field is added to the <nl> + / / msgdef as a part of this operation . <nl> + / / <nl> + / / The field may only have an OPTIONAL label , never REQUIRED or REPEATED . <nl> + / / <nl> + / / If | f | is already part of this MessageDef , this method performs no action <nl> + / / and returns true ( success ) . Thus , this method is idempotent . <nl> + bool AddField ( FieldDef * field , Status * s ) ; <nl> + bool AddField ( const reffed_ptr < FieldDef > & field , Status * s ) ; <nl> + <nl> + / / Looks up by name . <nl> + const FieldDef * FindFieldByName ( const char * name , size_t len ) const ; <nl> + FieldDef * FindFieldByName ( const char * name , size_t len ) ; <nl> + const FieldDef * FindFieldByName ( const char * name ) const { <nl> + return FindFieldByName ( name , strlen ( name ) ) ; <nl> + } <nl> + FieldDef * FindFieldByName ( const char * name ) { <nl> + return FindFieldByName ( name , strlen ( name ) ) ; <nl> + } <nl> + <nl> + template < class T > <nl> + FieldDef * FindFieldByName ( const T & str ) { <nl> + return FindFieldByName ( str . c_str ( ) , str . size ( ) ) ; <nl> + } <nl> + template < class T > <nl> + const FieldDef * FindFieldByName ( const T & str ) const { <nl> + return FindFieldByName ( str . c_str ( ) , str . size ( ) ) ; <nl> + } <nl> + <nl> + / / Looks up by tag number . <nl> + const FieldDef * FindFieldByNumber ( uint32_t num ) const ; <nl> + <nl> + / / Returns a new OneofDef with all the same fields . The OneofDef will be owned <nl> + / / by the given owner . <nl> + OneofDef * Dup ( const void * owner ) const ; <nl> + <nl> + / / Iteration over fields . The order is undefined . <nl> + class iterator : public std : : iterator < std : : forward_iterator_tag , FieldDef * > { <nl> + public : <nl> + explicit iterator ( OneofDef * md ) ; <nl> + static iterator end ( OneofDef * md ) ; <nl> + <nl> + void operator + + ( ) ; <nl> + FieldDef * operator * ( ) const ; <nl> + bool operator ! = ( const iterator & other ) const ; <nl> + bool operator = = ( const iterator & other ) const ; <nl> + <nl> + private : <nl> + upb_oneof_iter iter_ ; <nl> + } ; <nl> + <nl> + class const_iterator <nl> + : public std : : iterator < std : : forward_iterator_tag , const FieldDef * > { <nl> + public : <nl> + explicit const_iterator ( const OneofDef * md ) ; <nl> + static const_iterator end ( const OneofDef * md ) ; <nl> + <nl> + void operator + + ( ) ; <nl> + const FieldDef * operator * ( ) const ; <nl> + bool operator ! = ( const const_iterator & other ) const ; <nl> + bool operator = = ( const const_iterator & other ) const ; <nl> + <nl> + private : <nl> + upb_oneof_iter iter_ ; <nl> + } ; <nl> + <nl> + iterator begin ( ) ; <nl> + iterator end ( ) ; <nl> + const_iterator begin ( ) const ; <nl> + const_iterator end ( ) const ; <nl> + <nl> + private : <nl> + UPB_DISALLOW_POD_OPS ( OneofDef , upb : : OneofDef ) ; <nl> + ) , <nl> + UPB_DEFINE_STRUCT ( upb_oneofdef , upb_def , <nl> + upb_strtable ntof ; <nl> + upb_inttable itof ; <nl> + const upb_msgdef * parent ; <nl> + ) ) ; <nl> + <nl> + # define UPB_ONEOFDEF_INIT ( name , ntof , itof , refs , ref2s ) \ <nl> + { UPB_DEF_INIT ( name , UPB_DEF_ENUM , refs , ref2s ) , ntof , itof } <nl> + <nl> + UPB_BEGIN_EXTERN_C / / { <nl> + <nl> + / / Native C API . <nl> + upb_oneofdef * upb_oneofdef_new ( const void * owner ) ; <nl> + upb_oneofdef * upb_oneofdef_dup ( const upb_oneofdef * o , const void * owner ) ; <nl> + <nl> + / / From upb_refcounted . <nl> + void upb_oneofdef_unref ( const upb_oneofdef * o , const void * owner ) ; <nl> + bool upb_oneofdef_isfrozen ( const upb_oneofdef * e ) ; <nl> + void upb_oneofdef_ref ( const upb_oneofdef * o , const void * owner ) ; <nl> + void upb_oneofdef_donateref ( const upb_oneofdef * m , const void * from , <nl> + const void * to ) ; <nl> + void upb_oneofdef_checkref ( const upb_oneofdef * o , const void * owner ) ; <nl> + <nl> + const char * upb_oneofdef_name ( const upb_oneofdef * o ) ; <nl> + bool upb_oneofdef_setname ( upb_oneofdef * o , const char * name , upb_status * s ) ; <nl> + <nl> + const upb_msgdef * upb_oneofdef_containingtype ( const upb_oneofdef * o ) ; <nl> + int upb_oneofdef_numfields ( const upb_oneofdef * o ) ; <nl> + bool upb_oneofdef_addfield ( upb_oneofdef * o , upb_fielddef * f , <nl> + const void * ref_donor , <nl> + upb_status * s ) ; <nl> + <nl> + / / Oneof lookups : <nl> + / / - ntof : look up a field by name . <nl> + / / - ntofz : look up a field by name ( as a null - terminated string ) . <nl> + / / - itof : look up a field by number . <nl> + const upb_fielddef * upb_oneofdef_ntof ( const upb_oneofdef * o , <nl> + const char * name , size_t length ) ; <nl> + UPB_INLINE const upb_fielddef * upb_oneofdef_ntofz ( const upb_oneofdef * o , <nl> + const char * name ) { <nl> + return upb_oneofdef_ntof ( o , name , strlen ( name ) ) ; <nl> + } <nl> + const upb_fielddef * upb_oneofdef_itof ( const upb_oneofdef * o , uint32_t num ) ; <nl> + <nl> + / / upb_oneof_iter i ; <nl> + / / for ( upb_oneof_begin ( & i , e ) ; ! upb_oneof_done ( & i ) ; upb_oneof_next ( & i ) ) { <nl> + / / / / . . . <nl> + / / } <nl> + void upb_oneof_begin ( upb_oneof_iter * iter , const upb_oneofdef * o ) ; <nl> + void upb_oneof_next ( upb_oneof_iter * iter ) ; <nl> + bool upb_oneof_done ( upb_oneof_iter * iter ) ; <nl> + upb_fielddef * upb_oneof_iter_field ( const upb_oneof_iter * iter ) ; <nl> + void upb_oneof_iter_setdone ( upb_oneof_iter * iter ) ; <nl> + <nl> + UPB_END_EXTERN_C / / } <nl> <nl> # ifdef __cplusplus <nl> <nl> inline void FieldDef : : set_packed ( bool packed ) { <nl> inline const MessageDef * FieldDef : : containing_type ( ) const { <nl> return upb_fielddef_containingtype ( this ) ; <nl> } <nl> + inline const OneofDef * FieldDef : : containing_oneof ( ) const { <nl> + return upb_fielddef_containingoneof ( this ) ; <nl> + } <nl> inline const char * FieldDef : : containing_type_name ( ) { <nl> return upb_fielddef_containingtypename ( this ) ; <nl> } <nl> inline bool MessageDef : : Freeze ( Status * status ) { <nl> inline int MessageDef : : field_count ( ) const { <nl> return upb_msgdef_numfields ( this ) ; <nl> } <nl> + inline int MessageDef : : oneof_count ( ) const { <nl> + return upb_msgdef_numoneofs ( this ) ; <nl> + } <nl> inline bool MessageDef : : AddField ( upb_fielddef * f , Status * s ) { <nl> return upb_msgdef_addfield ( this , f , NULL , s ) ; <nl> } <nl> inline bool MessageDef : : AddField ( const reffed_ptr < FieldDef > & f , Status * s ) { <nl> return upb_msgdef_addfield ( this , f . get ( ) , NULL , s ) ; <nl> } <nl> + inline bool MessageDef : : AddOneof ( upb_oneofdef * o , Status * s ) { <nl> + return upb_msgdef_addoneof ( this , o , NULL , s ) ; <nl> + } <nl> + inline bool MessageDef : : AddOneof ( const reffed_ptr < OneofDef > & o , Status * s ) { <nl> + return upb_msgdef_addoneof ( this , o . get ( ) , NULL , s ) ; <nl> + } <nl> inline FieldDef * MessageDef : : FindFieldByNumber ( uint32_t number ) { <nl> return upb_msgdef_itof_mutable ( this , number ) ; <nl> } <nl> inline const FieldDef * MessageDef : : FindFieldByName ( const char * name , <nl> size_t len ) const { <nl> return upb_msgdef_ntof ( this , name , len ) ; <nl> } <nl> + inline OneofDef * MessageDef : : FindOneofByName ( const char * name , size_t len ) { <nl> + return upb_msgdef_ntoo_mutable ( this , name , len ) ; <nl> + } <nl> + inline const OneofDef * MessageDef : : FindOneofByName ( const char * name , <nl> + size_t len ) const { <nl> + return upb_msgdef_ntoo ( this , name , len ) ; <nl> + } <nl> inline MessageDef * MessageDef : : Dup ( const void * owner ) const { <nl> return upb_msgdef_dup ( this , owner ) ; <nl> } <nl> inline void MessageDef : : setmapentry ( bool map_entry ) { <nl> inline bool MessageDef : : mapentry ( ) const { <nl> return upb_msgdef_mapentry ( this ) ; <nl> } <nl> - inline MessageDef : : iterator MessageDef : : begin ( ) { return iterator ( this ) ; } <nl> - inline MessageDef : : iterator MessageDef : : end ( ) { return iterator : : end ( this ) ; } <nl> - inline MessageDef : : const_iterator MessageDef : : begin ( ) const { <nl> - return const_iterator ( this ) ; <nl> + inline MessageDef : : field_iterator MessageDef : : field_begin ( ) { <nl> + return field_iterator ( this ) ; <nl> } <nl> - inline MessageDef : : const_iterator MessageDef : : end ( ) const { <nl> - return const_iterator : : end ( this ) ; <nl> + inline MessageDef : : field_iterator MessageDef : : field_end ( ) { <nl> + return field_iterator : : end ( this ) ; <nl> + } <nl> + inline MessageDef : : const_field_iterator MessageDef : : field_begin ( ) const { <nl> + return const_field_iterator ( this ) ; <nl> + } <nl> + inline MessageDef : : const_field_iterator MessageDef : : field_end ( ) const { <nl> + return const_field_iterator : : end ( this ) ; <nl> + } <nl> + <nl> + inline MessageDef : : oneof_iterator MessageDef : : oneof_begin ( ) { <nl> + return oneof_iterator ( this ) ; <nl> + } <nl> + inline MessageDef : : oneof_iterator MessageDef : : oneof_end ( ) { <nl> + return oneof_iterator : : end ( this ) ; <nl> + } <nl> + inline MessageDef : : const_oneof_iterator MessageDef : : oneof_begin ( ) const { <nl> + return const_oneof_iterator ( this ) ; <nl> + } <nl> + inline MessageDef : : const_oneof_iterator MessageDef : : oneof_end ( ) const { <nl> + return const_oneof_iterator : : end ( this ) ; <nl> } <nl> <nl> - inline MessageDef : : iterator : : iterator ( MessageDef * md ) { <nl> - upb_msg_begin ( & iter_ , md ) ; <nl> + inline MessageDef : : field_iterator : : field_iterator ( MessageDef * md ) { <nl> + upb_msg_field_begin ( & iter_ , md ) ; <nl> } <nl> - inline MessageDef : : iterator MessageDef : : iterator : : end ( MessageDef * md ) { <nl> - MessageDef : : iterator iter ( md ) ; <nl> - upb_msg_iter_setdone ( & iter . iter_ ) ; <nl> + inline MessageDef : : field_iterator MessageDef : : field_iterator : : end ( <nl> + MessageDef * md ) { <nl> + MessageDef : : field_iterator iter ( md ) ; <nl> + upb_msg_field_iter_setdone ( & iter . iter_ ) ; <nl> return iter ; <nl> } <nl> - inline FieldDef * MessageDef : : iterator : : operator * ( ) const { <nl> + inline FieldDef * MessageDef : : field_iterator : : operator * ( ) const { <nl> return upb_msg_iter_field ( & iter_ ) ; <nl> } <nl> - inline void MessageDef : : iterator : : operator + + ( ) { return upb_msg_next ( & iter_ ) ; } <nl> - inline bool MessageDef : : iterator : : operator = = ( const iterator & other ) const { <nl> + inline void MessageDef : : field_iterator : : operator + + ( ) { <nl> + return upb_msg_field_next ( & iter_ ) ; <nl> + } <nl> + inline bool MessageDef : : field_iterator : : operator = = ( <nl> + const field_iterator & other ) const { <nl> return upb_inttable_iter_isequal ( & iter_ , & other . iter_ ) ; <nl> } <nl> - inline bool MessageDef : : iterator : : operator ! = ( const iterator & other ) const { <nl> + inline bool MessageDef : : field_iterator : : operator ! = ( <nl> + const field_iterator & other ) const { <nl> return ! ( * this = = other ) ; <nl> } <nl> <nl> - inline MessageDef : : const_iterator : : const_iterator ( const MessageDef * md ) { <nl> - upb_msg_begin ( & iter_ , md ) ; <nl> + inline MessageDef : : const_field_iterator : : const_field_iterator ( <nl> + const MessageDef * md ) { <nl> + upb_msg_field_begin ( & iter_ , md ) ; <nl> } <nl> - inline MessageDef : : const_iterator MessageDef : : const_iterator : : end ( <nl> + inline MessageDef : : const_field_iterator MessageDef : : const_field_iterator : : end ( <nl> const MessageDef * md ) { <nl> - MessageDef : : const_iterator iter ( md ) ; <nl> - upb_msg_iter_setdone ( & iter . iter_ ) ; <nl> + MessageDef : : const_field_iterator iter ( md ) ; <nl> + upb_msg_field_iter_setdone ( & iter . iter_ ) ; <nl> return iter ; <nl> } <nl> - inline const FieldDef * MessageDef : : const_iterator : : operator * ( ) const { <nl> + inline const FieldDef * MessageDef : : const_field_iterator : : operator * ( ) const { <nl> return upb_msg_iter_field ( & iter_ ) ; <nl> } <nl> - inline void MessageDef : : const_iterator : : operator + + ( ) { <nl> - return upb_msg_next ( & iter_ ) ; <nl> + inline void MessageDef : : const_field_iterator : : operator + + ( ) { <nl> + return upb_msg_field_next ( & iter_ ) ; <nl> } <nl> - inline bool MessageDef : : const_iterator : : operator = = ( <nl> - const const_iterator & other ) const { <nl> + inline bool MessageDef : : const_field_iterator : : operator = = ( <nl> + const const_field_iterator & other ) const { <nl> return upb_inttable_iter_isequal ( & iter_ , & other . iter_ ) ; <nl> } <nl> - inline bool MessageDef : : const_iterator : : operator ! = ( <nl> - const const_iterator & other ) const { <nl> + inline bool MessageDef : : const_field_iterator : : operator ! = ( <nl> + const const_field_iterator & other ) const { <nl> + return ! ( * this = = other ) ; <nl> + } <nl> + <nl> + inline MessageDef : : oneof_iterator : : oneof_iterator ( MessageDef * md ) { <nl> + upb_msg_oneof_begin ( & iter_ , md ) ; <nl> + } <nl> + inline MessageDef : : oneof_iterator MessageDef : : oneof_iterator : : end ( <nl> + MessageDef * md ) { <nl> + MessageDef : : oneof_iterator iter ( md ) ; <nl> + upb_msg_oneof_iter_setdone ( & iter . iter_ ) ; <nl> + return iter ; <nl> + } <nl> + inline OneofDef * MessageDef : : oneof_iterator : : operator * ( ) const { <nl> + return upb_msg_iter_oneof ( & iter_ ) ; <nl> + } <nl> + inline void MessageDef : : oneof_iterator : : operator + + ( ) { <nl> + return upb_msg_oneof_next ( & iter_ ) ; <nl> + } <nl> + inline bool MessageDef : : oneof_iterator : : operator = = ( <nl> + const oneof_iterator & other ) const { <nl> + return upb_strtable_iter_isequal ( & iter_ , & other . iter_ ) ; <nl> + } <nl> + inline bool MessageDef : : oneof_iterator : : operator ! = ( <nl> + const oneof_iterator & other ) const { <nl> + return ! ( * this = = other ) ; <nl> + } <nl> + <nl> + inline MessageDef : : const_oneof_iterator : : const_oneof_iterator ( <nl> + const MessageDef * md ) { <nl> + upb_msg_oneof_begin ( & iter_ , md ) ; <nl> + } <nl> + inline MessageDef : : const_oneof_iterator MessageDef : : const_oneof_iterator : : end ( <nl> + const MessageDef * md ) { <nl> + MessageDef : : const_oneof_iterator iter ( md ) ; <nl> + upb_msg_oneof_iter_setdone ( & iter . iter_ ) ; <nl> + return iter ; <nl> + } <nl> + inline const OneofDef * MessageDef : : const_oneof_iterator : : operator * ( ) const { <nl> + return upb_msg_iter_oneof ( & iter_ ) ; <nl> + } <nl> + inline void MessageDef : : const_oneof_iterator : : operator + + ( ) { <nl> + return upb_msg_oneof_next ( & iter_ ) ; <nl> + } <nl> + inline bool MessageDef : : const_oneof_iterator : : operator = = ( <nl> + const const_oneof_iterator & other ) const { <nl> + return upb_strtable_iter_isequal ( & iter_ , & other . iter_ ) ; <nl> + } <nl> + inline bool MessageDef : : const_oneof_iterator : : operator ! = ( <nl> + const const_oneof_iterator & other ) const { <nl> return ! ( * this = = other ) ; <nl> } <nl> <nl> inline const char * EnumDef : : Iterator : : name ( ) { <nl> } <nl> inline bool EnumDef : : Iterator : : Done ( ) { return upb_enum_done ( & iter_ ) ; } <nl> inline void EnumDef : : Iterator : : Next ( ) { return upb_enum_next ( & iter_ ) ; } <nl> + <nl> + inline reffed_ptr < OneofDef > OneofDef : : New ( ) { <nl> + upb_oneofdef * o = upb_oneofdef_new ( & o ) ; <nl> + return reffed_ptr < OneofDef > ( o , & o ) ; <nl> + } <nl> + inline bool OneofDef : : IsFrozen ( ) const { return upb_oneofdef_isfrozen ( this ) ; } <nl> + inline void OneofDef : : Ref ( const void * owner ) const { <nl> + return upb_oneofdef_ref ( this , owner ) ; <nl> + } <nl> + inline void OneofDef : : Unref ( const void * owner ) const { <nl> + return upb_oneofdef_unref ( this , owner ) ; <nl> + } <nl> + inline void OneofDef : : DonateRef ( const void * from , const void * to ) const { <nl> + return upb_oneofdef_donateref ( this , from , to ) ; <nl> + } <nl> + inline void OneofDef : : CheckRef ( const void * owner ) const { <nl> + return upb_oneofdef_checkref ( this , owner ) ; <nl> + } <nl> + inline const char * OneofDef : : full_name ( ) const { <nl> + return upb_oneofdef_name ( this ) ; <nl> + } <nl> + <nl> + inline const MessageDef * OneofDef : : containing_type ( ) const { <nl> + return upb_oneofdef_containingtype ( this ) ; <nl> + } <nl> + inline const char * OneofDef : : name ( ) const { <nl> + return upb_oneofdef_name ( this ) ; <nl> + } <nl> + inline bool OneofDef : : set_name ( const char * name , Status * s ) { <nl> + return upb_oneofdef_setname ( this , name , s ) ; <nl> + } <nl> + inline int OneofDef : : field_count ( ) const { <nl> + return upb_oneofdef_numfields ( this ) ; <nl> + } <nl> + inline bool OneofDef : : AddField ( FieldDef * field , Status * s ) { <nl> + return upb_oneofdef_addfield ( this , field , NULL , s ) ; <nl> + } <nl> + inline bool OneofDef : : AddField ( const reffed_ptr < FieldDef > & field , Status * s ) { <nl> + return upb_oneofdef_addfield ( this , field . get ( ) , NULL , s ) ; <nl> + } <nl> + inline const FieldDef * OneofDef : : FindFieldByName ( const char * name , <nl> + size_t len ) const { <nl> + return upb_oneofdef_ntof ( this , name , len ) ; <nl> + } <nl> + inline const FieldDef * OneofDef : : FindFieldByNumber ( uint32_t num ) const { <nl> + return upb_oneofdef_itof ( this , num ) ; <nl> + } <nl> + inline OneofDef : : iterator OneofDef : : begin ( ) { return iterator ( this ) ; } <nl> + inline OneofDef : : iterator OneofDef : : end ( ) { return iterator : : end ( this ) ; } <nl> + inline OneofDef : : const_iterator OneofDef : : begin ( ) const { <nl> + return const_iterator ( this ) ; <nl> + } <nl> + inline OneofDef : : const_iterator OneofDef : : end ( ) const { <nl> + return const_iterator : : end ( this ) ; <nl> + } <nl> + <nl> + inline OneofDef : : iterator : : iterator ( OneofDef * o ) { <nl> + upb_oneof_begin ( & iter_ , o ) ; <nl> + } <nl> + inline OneofDef : : iterator OneofDef : : iterator : : end ( OneofDef * o ) { <nl> + OneofDef : : iterator iter ( o ) ; <nl> + upb_oneof_iter_setdone ( & iter . iter_ ) ; <nl> + return iter ; <nl> + } <nl> + inline FieldDef * OneofDef : : iterator : : operator * ( ) const { <nl> + return upb_oneof_iter_field ( & iter_ ) ; <nl> + } <nl> + inline void OneofDef : : iterator : : operator + + ( ) { return upb_oneof_next ( & iter_ ) ; } <nl> + inline bool OneofDef : : iterator : : operator = = ( const iterator & other ) const { <nl> + return upb_inttable_iter_isequal ( & iter_ , & other . iter_ ) ; <nl> + } <nl> + inline bool OneofDef : : iterator : : operator ! = ( const iterator & other ) const { <nl> + return ! ( * this = = other ) ; <nl> + } <nl> + <nl> + inline OneofDef : : const_iterator : : const_iterator ( const OneofDef * md ) { <nl> + upb_oneof_begin ( & iter_ , md ) ; <nl> + } <nl> + inline OneofDef : : const_iterator OneofDef : : const_iterator : : end ( <nl> + const OneofDef * md ) { <nl> + OneofDef : : const_iterator iter ( md ) ; <nl> + upb_oneof_iter_setdone ( & iter . iter_ ) ; <nl> + return iter ; <nl> + } <nl> + inline const FieldDef * OneofDef : : const_iterator : : operator * ( ) const { <nl> + return upb_msg_iter_field ( & iter_ ) ; <nl> + } <nl> + inline void OneofDef : : const_iterator : : operator + + ( ) { <nl> + return upb_oneof_next ( & iter_ ) ; <nl> + } <nl> + inline bool OneofDef : : const_iterator : : operator = = ( <nl> + const const_iterator & other ) const { <nl> + return upb_inttable_iter_isequal ( & iter_ , & other . iter_ ) ; <nl> + } <nl> + inline bool OneofDef : : const_iterator : : operator ! = ( <nl> + const const_iterator & other ) const { <nl> + return ! ( * this = = other ) ; <nl> + } <nl> + <nl> } / / namespace upb <nl> # endif <nl> <nl> mmm a / ruby / google - protobuf . gemspec <nl> ppp b / ruby / google - protobuf . gemspec <nl> Gem : : Specification . new do | s | <nl> s . files = [ " lib / google / protobuf . rb " ] + <nl> # extension C source <nl> find_c_source ( " ext / google / protobuf_c " ) <nl> - s . test_files = ` git ls - files - - tests ` . split <nl> + s . test_files = [ " tests / basic . rb " , <nl> + " tests / stress . rb " , <nl> + " tests / generated_code_test . rb " ] <nl> end <nl> mmm a / ruby / tests / basic . rb <nl> ppp b / ruby / tests / basic . rb <nl> module BasicTest <nl> optional : key , : string , 1 <nl> optional : value , : message , 2 , " TestMessage2 " <nl> end <nl> + <nl> + add_message " OneofMessage " do <nl> + oneof : my_oneof do <nl> + optional : a , : string , 1 <nl> + optional : b , : int32 , 2 <nl> + optional : c , : message , 3 , " TestMessage2 " <nl> + optional : d , : enum , 4 , " TestEnum " <nl> + end <nl> + end <nl> end <nl> <nl> TestMessage = pool . lookup ( " TestMessage " ) . msgclass <nl> module BasicTest <nl> pool . lookup ( " MapMessageWireEquiv_entry1 " ) . msgclass <nl> MapMessageWireEquiv_entry2 = <nl> pool . lookup ( " MapMessageWireEquiv_entry2 " ) . msgclass <nl> + OneofMessage = pool . lookup ( " OneofMessage " ) . msgclass <nl> <nl> # mmmmmmmmmmmm test cases mmmmmmmmmmmmmmm <nl> <nl> def test_map_encode_decode <nl> " b " = > TestMessage2 . new ( : foo = > 2 ) } <nl> end <nl> <nl> + def test_oneof_descriptors <nl> + d = OneofMessage . descriptor <nl> + o = d . lookup_oneof ( " my_oneof " ) <nl> + assert o ! = nil <nl> + assert o . class = = Google : : Protobuf : : OneofDescriptor <nl> + assert o . name = = " my_oneof " <nl> + oneof_count = 0 <nl> + d . each_oneof { | oneof | <nl> + oneof_count + = 1 <nl> + assert oneof = = o <nl> + } <nl> + assert oneof_count = = 1 <nl> + assert o . count = = 4 <nl> + field_names = o . map { | f | f . name } . sort <nl> + assert field_names = = [ " a " , " b " , " c " , " d " ] <nl> + end <nl> + <nl> + def test_oneof <nl> + d = OneofMessage . new <nl> + assert d . a = = nil <nl> + assert d . b = = nil <nl> + assert d . c = = nil <nl> + assert d . d = = nil <nl> + assert d . my_oneof = = nil <nl> + <nl> + d . a = " hi " <nl> + assert d . a = = " hi " <nl> + assert d . b = = nil <nl> + assert d . c = = nil <nl> + assert d . d = = nil <nl> + assert d . my_oneof = = : a <nl> + <nl> + d . b = 42 <nl> + assert d . a = = nil <nl> + assert d . b = = 42 <nl> + assert d . c = = nil <nl> + assert d . d = = nil <nl> + assert d . my_oneof = = : b <nl> + <nl> + d . c = TestMessage2 . new ( : foo = > 100 ) <nl> + assert d . a = = nil <nl> + assert d . b = = nil <nl> + assert d . c . foo = = 100 <nl> + assert d . d = = nil <nl> + assert d . my_oneof = = : c <nl> + <nl> + d . d = : C <nl> + assert d . a = = nil <nl> + assert d . b = = nil <nl> + assert d . c = = nil <nl> + assert d . d = = : C <nl> + assert d . my_oneof = = : d <nl> + <nl> + d2 = OneofMessage . decode ( OneofMessage . encode ( d ) ) <nl> + assert d2 = = d <nl> + <nl> + encoded_field_a = OneofMessage . encode ( OneofMessage . new ( : a = > " string " ) ) <nl> + encoded_field_b = OneofMessage . encode ( OneofMessage . new ( : b = > 1000 ) ) <nl> + encoded_field_c = OneofMessage . encode ( <nl> + OneofMessage . new ( : c = > TestMessage2 . new ( : foo = > 1 ) ) ) <nl> + encoded_field_d = OneofMessage . encode ( OneofMessage . new ( : d = > : B ) ) <nl> + <nl> + d3 = OneofMessage . decode ( <nl> + encoded_field_c + encoded_field_a + encoded_field_d ) <nl> + assert d3 . a = = nil <nl> + assert d3 . b = = nil <nl> + assert d3 . c = = nil <nl> + assert d3 . d = = : B <nl> + <nl> + d4 = OneofMessage . decode ( <nl> + encoded_field_c + encoded_field_a + encoded_field_d + <nl> + encoded_field_c ) <nl> + assert d4 . a = = nil <nl> + assert d4 . b = = nil <nl> + assert d4 . c . foo = = 1 <nl> + assert d4 . d = = nil <nl> + <nl> + d5 = OneofMessage . new ( : a = > " hello " ) <nl> + assert d5 . a ! = nil <nl> + d5 . a = nil <nl> + assert d5 . a = = nil <nl> + assert OneofMessage . encode ( d5 ) = = ' ' <nl> + assert d5 . my_oneof = = nil <nl> + end <nl> + <nl> def test_enum_field <nl> m = TestMessage . new <nl> assert m . optional_enum = = : Default <nl> def test_deep_copy <nl> assert m . repeated_msg [ 0 ] . object_id ! = m2 . repeated_msg [ 0 ] . object_id <nl> end <nl> <nl> + def test_eq <nl> + m = TestMessage . new ( : optional_int32 = > 42 , <nl> + : repeated_int32 = > [ 1 , 2 , 3 ] ) <nl> + m2 = TestMessage . new ( : optional_int32 = > 43 , <nl> + : repeated_int32 = > [ 1 , 2 , 3 ] ) <nl> + assert m ! = m2 <nl> + end <nl> + <nl> def test_enum_lookup <nl> assert TestEnum : : A = = 1 <nl> assert TestEnum : : B = = 2 <nl> new file mode 100644 <nl> index 0000000000 . . b1d6323243 <nl> mmm / dev / null <nl> ppp b / ruby / tests / generated_code . proto <nl> <nl> + syntax = " proto3 " ; <nl> + <nl> + package A . B . C ; <nl> + <nl> + message TestMessage { <nl> + optional int32 optional_int32 = 1 ; <nl> + optional int64 optional_int64 = 2 ; <nl> + optional uint32 optional_uint32 = 3 ; <nl> + optional uint64 optional_uint64 = 4 ; <nl> + optional bool optional_bool = 5 ; <nl> + optional double optional_double = 6 ; <nl> + optional float optional_float = 7 ; <nl> + optional string optional_string = 8 ; <nl> + optional bytes optional_bytes = 9 ; <nl> + optional TestEnum optional_enum = 10 ; <nl> + optional TestMessage optional_msg = 11 ; <nl> + <nl> + repeated int32 repeated_int32 = 21 ; <nl> + repeated int64 repeated_int64 = 22 ; <nl> + repeated uint32 repeated_uint32 = 23 ; <nl> + repeated uint64 repeated_uint64 = 24 ; <nl> + repeated bool repeated_bool = 25 ; <nl> + repeated double repeated_double = 26 ; <nl> + repeated float repeated_float = 27 ; <nl> + repeated string repeated_string = 28 ; <nl> + repeated bytes repeated_bytes = 29 ; <nl> + repeated TestEnum repeated_enum = 30 ; <nl> + repeated TestMessage repeated_msg = 31 ; <nl> + <nl> + oneof my_oneof { <nl> + int32 oneof_int32 = 41 ; <nl> + int64 oneof_int64 = 42 ; <nl> + uint32 oneof_uint32 = 43 ; <nl> + uint64 oneof_uint64 = 44 ; <nl> + bool oneof_bool = 45 ; <nl> + double oneof_double = 46 ; <nl> + float oneof_float = 47 ; <nl> + string oneof_string = 48 ; <nl> + bytes oneof_bytes = 49 ; <nl> + TestEnum oneof_enum = 50 ; <nl> + TestMessage oneof_msg = 51 ; <nl> + } <nl> + <nl> + map < int32 , string > map_int32_string = 61 ; <nl> + map < int64 , string > map_int64_string = 62 ; <nl> + map < uint32 , string > map_uint32_string = 63 ; <nl> + map < uint64 , string > map_uint64_string = 64 ; <nl> + map < bool , string > map_bool_string = 65 ; <nl> + map < string , string > map_string_string = 66 ; <nl> + map < string , TestMessage > map_string_msg = 67 ; <nl> + map < string , TestEnum > map_string_enum = 68 ; <nl> + map < string , int32 > map_string_int32 = 69 ; <nl> + map < string , bool > map_string_bool = 70 ; <nl> + <nl> + message NestedMessage { <nl> + optional int32 foo = 1 ; <nl> + } <nl> + <nl> + optional NestedMessage nested_message = 80 ; <nl> + } <nl> + <nl> + enum TestEnum { <nl> + Default = 0 ; <nl> + A = 1 ; <nl> + B = 2 ; <nl> + C = 3 ; <nl> + } <nl> new file mode 100644 <nl> index 0000000000 . . db762ad9f2 <nl> mmm / dev / null <nl> ppp b / ruby / tests / generated_code . rb <nl> <nl> + # Generated by the protocol buffer compiler . DO NOT EDIT ! <nl> + # source : generated_code . proto <nl> + <nl> + require ' google / protobuf ' <nl> + <nl> + Google : : Protobuf : : DescriptorPool . generated_pool . build do <nl> + add_message " A . B . C . TestMessage " do <nl> + optional : optional_int32 , : int32 , 1 <nl> + optional : optional_int64 , : int64 , 2 <nl> + optional : optional_uint32 , : uint32 , 3 <nl> + optional : optional_uint64 , : uint64 , 4 <nl> + optional : optional_bool , : bool , 5 <nl> + optional : optional_double , : double , 6 <nl> + optional : optional_float , : float , 7 <nl> + optional : optional_string , : string , 8 <nl> + optional : optional_bytes , : string , 9 <nl> + optional : optional_enum , : enum , 10 , " A . B . C . TestEnum " <nl> + optional : optional_msg , : message , 11 , " A . B . C . TestMessage " <nl> + repeated : repeated_int32 , : int32 , 21 <nl> + repeated : repeated_int64 , : int64 , 22 <nl> + repeated : repeated_uint32 , : uint32 , 23 <nl> + repeated : repeated_uint64 , : uint64 , 24 <nl> + repeated : repeated_bool , : bool , 25 <nl> + repeated : repeated_double , : double , 26 <nl> + repeated : repeated_float , : float , 27 <nl> + repeated : repeated_string , : string , 28 <nl> + repeated : repeated_bytes , : string , 29 <nl> + repeated : repeated_enum , : enum , 30 , " A . B . C . TestEnum " <nl> + repeated : repeated_msg , : message , 31 , " A . B . C . TestMessage " <nl> + repeated : map_int32_string , : message , 61 , " A . B . C . TestMessage . MapInt32StringEntry " <nl> + repeated : map_int64_string , : message , 62 , " A . B . C . TestMessage . MapInt64StringEntry " <nl> + repeated : map_uint32_string , : message , 63 , " A . B . C . TestMessage . MapUint32StringEntry " <nl> + repeated : map_uint64_string , : message , 64 , " A . B . C . TestMessage . MapUint64StringEntry " <nl> + repeated : map_bool_string , : message , 65 , " A . B . C . TestMessage . MapBoolStringEntry " <nl> + repeated : map_string_string , : message , 66 , " A . B . C . TestMessage . MapStringStringEntry " <nl> + repeated : map_string_msg , : message , 67 , " A . B . C . TestMessage . MapStringMsgEntry " <nl> + repeated : map_string_enum , : message , 68 , " A . B . C . TestMessage . MapStringEnumEntry " <nl> + repeated : map_string_int32 , : message , 69 , " A . B . C . TestMessage . MapStringInt32Entry " <nl> + repeated : map_string_bool , : message , 70 , " A . B . C . TestMessage . MapStringBoolEntry " <nl> + optional : nested_message , : message , 80 , " A . B . C . TestMessage . NestedMessage " <nl> + oneof : my_oneof do <nl> + optional : oneof_int32 , : int32 , 41 <nl> + optional : oneof_int64 , : int64 , 42 <nl> + optional : oneof_uint32 , : uint32 , 43 <nl> + optional : oneof_uint64 , : uint64 , 44 <nl> + optional : oneof_bool , : bool , 45 <nl> + optional : oneof_double , : double , 46 <nl> + optional : oneof_float , : float , 47 <nl> + optional : oneof_string , : string , 48 <nl> + optional : oneof_bytes , : string , 49 <nl> + optional : oneof_enum , : enum , 50 , " A . B . C . TestEnum " <nl> + optional : oneof_msg , : message , 51 , " A . B . C . TestMessage " <nl> + end <nl> + end <nl> + add_message " A . B . C . TestMessage . MapInt32StringEntry " do <nl> + optional : key , : int32 , 1 <nl> + optional : value , : string , 2 <nl> + end <nl> + add_message " A . B . C . TestMessage . MapInt64StringEntry " do <nl> + optional : key , : int64 , 1 <nl> + optional : value , : string , 2 <nl> + end <nl> + add_message " A . B . C . TestMessage . MapUint32StringEntry " do <nl> + optional : key , : uint32 , 1 <nl> + optional : value , : string , 2 <nl> + end <nl> + add_message " A . B . C . TestMessage . MapUint64StringEntry " do <nl> + optional : key , : uint64 , 1 <nl> + optional : value , : string , 2 <nl> + end <nl> + add_message " A . B . C . TestMessage . MapBoolStringEntry " do <nl> + optional : key , : bool , 1 <nl> + optional : value , : string , 2 <nl> + end <nl> + add_message " A . B . C . TestMessage . MapStringStringEntry " do <nl> + optional : key , : string , 1 <nl> + optional : value , : string , 2 <nl> + end <nl> + add_message " A . B . C . TestMessage . MapStringMsgEntry " do <nl> + optional : key , : string , 1 <nl> + optional : value , : message , 2 , " A . B . C . TestMessage " <nl> + end <nl> + add_message " A . B . C . TestMessage . MapStringEnumEntry " do <nl> + optional : key , : string , 1 <nl> + optional : value , : enum , 2 , " A . B . C . TestEnum " <nl> + end <nl> + add_message " A . B . C . TestMessage . MapStringInt32Entry " do <nl> + optional : key , : string , 1 <nl> + optional : value , : int32 , 2 <nl> + end <nl> + add_message " A . B . C . TestMessage . MapStringBoolEntry " do <nl> + optional : key , : string , 1 <nl> + optional : value , : bool , 2 <nl> + end <nl> + add_message " A . B . C . TestMessage . NestedMessage " do <nl> + optional : foo , : int32 , 1 <nl> + end <nl> + add_enum " A . B . C . TestEnum " do <nl> + value : Default , 0 <nl> + value : A , 1 <nl> + value : B , 2 <nl> + value : C , 3 <nl> + end <nl> + end <nl> + <nl> + module A <nl> + module B <nl> + module C <nl> + TestMessage = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage " ) . msgclass <nl> + TestMessage : : MapInt32StringEntry = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage . MapInt32StringEntry " ) . msgclass <nl> + TestMessage : : MapInt64StringEntry = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage . MapInt64StringEntry " ) . msgclass <nl> + TestMessage : : MapUint32StringEntry = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage . MapUint32StringEntry " ) . msgclass <nl> + TestMessage : : MapUint64StringEntry = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage . MapUint64StringEntry " ) . msgclass <nl> + TestMessage : : MapBoolStringEntry = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage . MapBoolStringEntry " ) . msgclass <nl> + TestMessage : : MapStringStringEntry = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage . MapStringStringEntry " ) . msgclass <nl> + TestMessage : : MapStringMsgEntry = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage . MapStringMsgEntry " ) . msgclass <nl> + TestMessage : : MapStringEnumEntry = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage . MapStringEnumEntry " ) . msgclass <nl> + TestMessage : : MapStringInt32Entry = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage . MapStringInt32Entry " ) . msgclass <nl> + TestMessage : : MapStringBoolEntry = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage . MapStringBoolEntry " ) . msgclass <nl> + TestMessage : : NestedMessage = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestMessage . NestedMessage " ) . msgclass <nl> + TestEnum = Google : : Protobuf : : DescriptorPool . generated_pool . lookup ( " A . B . C . TestEnum " ) . enummodule <nl> + end <nl> + end <nl> + end <nl> new file mode 100644 <nl> index 0000000000 . . daef357a10 <nl> mmm / dev / null <nl> ppp b / ruby / tests / generated_code_test . rb <nl> <nl> + # ! / usr / bin / ruby <nl> + <nl> + # generated_code . rb is in the same directory as this test . <nl> + $ LOAD_PATH . unshift ( File . expand_path ( File . dirname ( __FILE__ ) ) ) <nl> + <nl> + require ' generated_code ' <nl> + require ' test / unit ' <nl> + <nl> + class GeneratedCodeTest < Test : : Unit : : TestCase <nl> + def test_generated_msg <nl> + # just test that we can instantiate the message . The purpose of this test <nl> + # is to ensure that the output of the code generator is valid Ruby and <nl> + # successfully creates message definitions and classes , not to test every <nl> + # aspect of the extension ( basic . rb is for that ) . <nl> + m = A : : B : : C : : TestMessage . new ( ) <nl> + end <nl> + end <nl> mmm a / src / Makefile . am <nl> ppp b / src / Makefile . am <nl> protobuf_test_SOURCES = \ <nl> google / protobuf / compiler / java / java_plugin_unittest . cc \ <nl> google / protobuf / compiler / java / java_doc_comment_unittest . cc \ <nl> google / protobuf / compiler / python / python_plugin_unittest . cc \ <nl> + google / protobuf / compiler / ruby / ruby_generator_unittest . cc \ <nl> $ ( COMMON_TEST_SOURCES ) <nl> nodist_protobuf_test_SOURCES = $ ( protoc_outputs ) <nl> <nl> mmm a / src / google / protobuf / compiler / ruby / ruby_generator . cc <nl> ppp b / src / google / protobuf / compiler / ruby / ruby_generator . cc <nl> std : : string TypeName ( const google : : protobuf : : FieldDescriptor * field ) { <nl> } <nl> } <nl> <nl> + void GenerateField ( const google : : protobuf : : FieldDescriptor * field , <nl> + google : : protobuf : : io : : Printer * printer ) { <nl> + printer - > Print ( <nl> + " $ label $ : $ name $ , " , <nl> + " label " , LabelForField ( field ) , <nl> + " name " , field - > name ( ) ) ; <nl> + printer - > Print ( <nl> + " : $ type $ , $ number $ " , <nl> + " type " , TypeName ( field ) , <nl> + " number " , IntToString ( field - > number ( ) ) ) ; <nl> + if ( field - > cpp_type ( ) = = FieldDescriptor : : CPPTYPE_MESSAGE ) { <nl> + printer - > Print ( <nl> + " , \ " $ subtype $ \ " \ n " , <nl> + " subtype " , field - > message_type ( ) - > full_name ( ) ) ; <nl> + } else if ( field - > cpp_type ( ) = = FieldDescriptor : : CPPTYPE_ENUM ) { <nl> + printer - > Print ( <nl> + " , \ " $ subtype $ \ " \ n " , <nl> + " subtype " , field - > enum_type ( ) - > full_name ( ) ) ; <nl> + } else { <nl> + printer - > Print ( " \ n " ) ; <nl> + } <nl> + } <nl> + <nl> + void GenerateOneof ( const google : : protobuf : : OneofDescriptor * oneof , <nl> + google : : protobuf : : io : : Printer * printer ) { <nl> + printer - > Print ( <nl> + " oneof : $ name $ do \ n " , <nl> + " name " , oneof - > name ( ) ) ; <nl> + printer - > Indent ( ) ; <nl> + <nl> + for ( int i = 0 ; i < oneof - > field_count ( ) ; i + + ) { <nl> + const FieldDescriptor * field = oneof - > field ( i ) ; <nl> + GenerateField ( field , printer ) ; <nl> + } <nl> + <nl> + printer - > Outdent ( ) ; <nl> + printer - > Print ( " end \ n " ) ; <nl> + } <nl> + <nl> void GenerateMessage ( const google : : protobuf : : Descriptor * message , <nl> google : : protobuf : : io : : Printer * printer ) { <nl> printer - > Print ( <nl> void GenerateMessage ( const google : : protobuf : : Descriptor * message , <nl> <nl> for ( int i = 0 ; i < message - > field_count ( ) ; i + + ) { <nl> const FieldDescriptor * field = message - > field ( i ) ; <nl> - printer - > Print ( <nl> - " $ label $ : $ name $ , " , <nl> - " label " , LabelForField ( field ) , <nl> - " name " , field - > name ( ) ) ; <nl> - printer - > Print ( <nl> - " : $ type $ , $ number $ " , <nl> - " type " , TypeName ( field ) , <nl> - " number " , IntToString ( field - > number ( ) ) ) ; <nl> - if ( field - > cpp_type ( ) = = FieldDescriptor : : CPPTYPE_MESSAGE ) { <nl> - printer - > Print ( <nl> - " , \ " $ subtype $ \ " \ n " , <nl> - " subtype " , field - > message_type ( ) - > full_name ( ) ) ; <nl> - } else if ( field - > cpp_type ( ) = = FieldDescriptor : : CPPTYPE_ENUM ) { <nl> - printer - > Print ( <nl> - " , \ " $ subtype $ \ " \ n " , <nl> - " subtype " , field - > enum_type ( ) - > full_name ( ) ) ; <nl> - } else { <nl> - printer - > Print ( " \ n " ) ; <nl> + if ( ! field - > containing_oneof ( ) ) { <nl> + GenerateField ( field , printer ) ; <nl> } <nl> } <nl> <nl> + for ( int i = 0 ; i < message - > oneof_decl_count ( ) ; i + + ) { <nl> + const OneofDescriptor * oneof = message - > oneof_decl ( i ) ; <nl> + GenerateOneof ( oneof , printer ) ; <nl> + } <nl> + <nl> printer - > Outdent ( ) ; <nl> printer - > Print ( " end \ n " ) ; <nl> <nl> new file mode 100644 <nl> index 0000000000 . . e35ca695b5 <nl> mmm / dev / null <nl> ppp b / src / google / protobuf / compiler / ruby / ruby_generator_unittest . cc <nl> <nl> + / / Protocol Buffers - Google ' s data interchange format <nl> + / / Copyright 2014 Google Inc . All rights reserved . <nl> + / / https : / / developers . google . com / protocol - buffers / <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without <nl> + / / modification , are permitted provided that the following conditions are <nl> + / / met : <nl> + / / <nl> + / / * Redistributions of source code must retain the above copyright <nl> + / / notice , this list of conditions and the following disclaimer . <nl> + / / * Redistributions in binary form must reproduce the above <nl> + / / copyright notice , this list of conditions and the following disclaimer <nl> + / / in the documentation and / or other materials provided with the <nl> + / / distribution . <nl> + / / * Neither the name of Google Inc . nor the names of its <nl> + / / contributors may be used to endorse or promote products derived from <nl> + / / this software without specific prior written permission . <nl> + / / <nl> + / / THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <nl> + / / " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT <nl> + / / LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR <nl> + / / A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT <nl> + / / OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , <nl> + / / SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT <nl> + / / LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + / / DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + / / THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + / / ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE <nl> + / / OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + <nl> + # include < memory > <nl> + <nl> + # include < google / protobuf / compiler / ruby / ruby_generator . h > <nl> + # include < google / protobuf / compiler / command_line_interface . h > <nl> + # include < google / protobuf / io / zero_copy_stream . h > <nl> + # include < google / protobuf / io / printer . h > <nl> + <nl> + # include < google / protobuf / testing / googletest . h > <nl> + # include < gtest / gtest . h > <nl> + # include < google / protobuf / testing / file . h > <nl> + <nl> + namespace google { <nl> + namespace protobuf { <nl> + namespace compiler { <nl> + namespace ruby { <nl> + namespace { <nl> + <nl> + string FindRubyTestDir ( ) { <nl> + / / Inspired by TestSourceDir ( ) in src / google / protobuf / testing / googletest . cc . <nl> + string prefix = " . " ; <nl> + while ( ! File : : Exists ( prefix + " / ruby / tests " ) ) { <nl> + if ( ! File : : Exists ( prefix ) ) { <nl> + GOOGLE_LOG ( FATAL ) <nl> + < < " Could not find Ruby test directory . Please run tests from " <nl> + " somewhere within the protobuf source package . " ; <nl> + } <nl> + prefix + = " / . . " ; <nl> + } <nl> + return prefix + " / ruby / tests " ; <nl> + } <nl> + <nl> + / / This test is a simple golden - file test over the output of the Ruby code <nl> + / / generator . When we make changes to the Ruby extension and alter the Ruby code <nl> + / / generator to use those changes , we should ( i ) manually test the output of the <nl> + / / code generator with the extension , and ( ii ) update the golden output above . <nl> + / / Some day , we may integrate build systems between protoc and the language <nl> + / / extensions to the point where we can do this test in a more automated way . <nl> + <nl> + TEST ( RubyGeneratorTest , GeneratorTest ) { <nl> + string ruby_tests = FindRubyTestDir ( ) ; <nl> + <nl> + google : : protobuf : : compiler : : CommandLineInterface cli ; <nl> + cli . SetInputsAreProtoPathRelative ( true ) ; <nl> + <nl> + ruby : : Generator ruby_generator ; <nl> + cli . RegisterGenerator ( " - - ruby_out " , & ruby_generator , " " ) ; <nl> + <nl> + / / Copy generated_code . proto to the temporary test directory . <nl> + string test_input ; <nl> + GOOGLE_CHECK_OK ( File : : GetContents ( <nl> + ruby_tests + " / generated_code . proto " , <nl> + & test_input , <nl> + true ) ) ; <nl> + GOOGLE_CHECK_OK ( File : : SetContents ( <nl> + TestTempDir ( ) + " / generated_code . proto " , <nl> + test_input , <nl> + true ) ) ; <nl> + <nl> + / / Invoke the proto compiler ( we will be inside TestTempDir ( ) at this point ) . <nl> + string ruby_out = " - - ruby_out = " + TestTempDir ( ) ; <nl> + string proto_path = " - - proto_path = " + TestTempDir ( ) ; <nl> + const char * argv [ ] = { <nl> + " protoc " , <nl> + ruby_out . c_str ( ) , <nl> + proto_path . c_str ( ) , <nl> + " generated_code . proto " , <nl> + } ; <nl> + <nl> + EXPECT_EQ ( 0 , cli . Run ( 4 , argv ) ) ; <nl> + <nl> + / / Load the generated output and compare to the expected result . <nl> + string output ; <nl> + GOOGLE_CHECK_OK ( File : : GetContents ( <nl> + TestTempDir ( ) + " / generated_code . rb " , <nl> + & output , <nl> + true ) ) ; <nl> + string expected_output ; <nl> + GOOGLE_CHECK_OK ( File : : GetContents ( <nl> + ruby_tests + " / generated_code . rb " , <nl> + & expected_output , <nl> + true ) ) ; <nl> + EXPECT_EQ ( expected_output , output ) ; <nl> + } <nl> + <nl> + } / / namespace <nl> + } / / namespace ruby <nl> + } / / namespace compiler <nl> + } / / namespace protobuf <nl> + } / / namespace google <nl>
Merge pull request from cfallin / ruby - oneof
protocolbuffers/protobuf
17e4419188e5873c43d462d493fcbb2cc668aa71
2015-02-02T21:29:15Z
mmm a / README <nl> ppp b / README <nl> aria2 is in very early development stage . Currently it has following features : <nl> * It can run as a daemon process . <nl> * BitTorrent protocol support with fast extension . <nl> * Selective download in multi - file torrent <nl> - * Metalink version 3 . 0 support ( HTTP / FTP only ) . <nl> + * Metalink version 3 . 0 support ( HTTP / FTP / BitTorrent ) . <nl> <nl> 3 . How to build <nl> mmmmmmmmmmmmmmm <nl> files . <nl> <nl> 6 . Metalink <nl> mmmmmmmmm - - <nl> - The current implementation only supports HTTP / FTP downloading in Metalink . <nl> - BitTorrent and other P2P protocols are ignored . <nl> + The current implementation supports HTTP / FTP / BitTorrent . <nl> + BitTorrent always has precedence over HTTP / FTP . <nl> + The other P2P protocols are ignored . <nl> <nl> For checksum checking , both MD5 and SHA1 are supported . If both values are <nl> provided , then aria2 uses SHA1 . If checksum checking is failed , aria2 doesn ' t <nl>
Updated doc
aria2/aria2
8b8e769aaa896a3425c6ed0b0f952bf6a424745e
2006-08-07T16:47:52Z
mmm a / deps / build . jl <nl> ppp b / deps / build . jl <nl> if ! libmxnet_detected <nl> ` cp make / config . mk config . mk ` <nl> @ osx_only ` cp make / osx . mk config . mk ` <nl> ` sed - i - s ' s / USE_OPENCV = 1 / USE_OPENCV = 0 / ' config . mk ` <nl> + ` cp . . / . . / cblas . h include / cblas . h ` <nl> ` make USE_BLAS = openblas MSHADOW_LDFLAGS = " $ openblas_path " - j ` <nl> ` cp lib / libmxnet . so $ _libdir ` <nl> end ) <nl> new file mode 100644 <nl> index 00000000000 . . 941b570c78d <nl> mmm / dev / null <nl> ppp b / deps / cblas . h <nl> <nl> + # ifndef CBLAS_H <nl> + # define CBLAS_H <nl> + # include < stddef . h > <nl> + <nl> + / / This header file copied from the Netlib libblas distribution package <nl> + <nl> + / * Allow the use in C + + code . * / <nl> + # ifdef __cplusplus <nl> + extern " C " <nl> + { <nl> + # endif <nl> + <nl> + / * <nl> + * Enumerated and derived types <nl> + * / <nl> + # define CBLAS_INDEX size_t / * this may vary between platforms * / <nl> + <nl> + enum CBLAS_ORDER { CblasRowMajor = 101 , CblasColMajor = 102 } ; <nl> + enum CBLAS_TRANSPOSE { CblasNoTrans = 111 , CblasTrans = 112 , CblasConjTrans = 113 } ; <nl> + enum CBLAS_UPLO { CblasUpper = 121 , CblasLower = 122 } ; <nl> + enum CBLAS_DIAG { CblasNonUnit = 131 , CblasUnit = 132 } ; <nl> + enum CBLAS_SIDE { CblasLeft = 141 , CblasRight = 142 } ; <nl> + <nl> + / * <nl> + * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + * Prototypes for level 1 BLAS functions ( complex are recast as routines ) <nl> + * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + * / <nl> + float cblas_sdsdot ( const int N , const float alpha , const float * X , <nl> + const int incX , const float * Y , const int incY ) ; <nl> + double cblas_dsdot ( const int N , const float * X , const int incX , const float * Y , <nl> + const int incY ) ; <nl> + float cblas_sdot ( const int N , const float * X , const int incX , <nl> + const float * Y , const int incY ) ; <nl> + double cblas_ddot ( const int N , const double * X , const int incX , <nl> + const double * Y , const int incY ) ; <nl> + <nl> + / * <nl> + * Functions having prefixes Z and C only <nl> + * / <nl> + void cblas_cdotu_sub ( const int N , const void * X , const int incX , <nl> + const void * Y , const int incY , void * dotu ) ; <nl> + void cblas_cdotc_sub ( const int N , const void * X , const int incX , <nl> + const void * Y , const int incY , void * dotc ) ; <nl> + <nl> + void cblas_zdotu_sub ( const int N , const void * X , const int incX , <nl> + const void * Y , const int incY , void * dotu ) ; <nl> + void cblas_zdotc_sub ( const int N , const void * X , const int incX , <nl> + const void * Y , const int incY , void * dotc ) ; <nl> + <nl> + <nl> + / * <nl> + * Functions having prefixes S D SC DZ <nl> + * / <nl> + float cblas_snrm2 ( const int N , const float * X , const int incX ) ; <nl> + float cblas_sasum ( const int N , const float * X , const int incX ) ; <nl> + <nl> + double cblas_dnrm2 ( const int N , const double * X , const int incX ) ; <nl> + double cblas_dasum ( const int N , const double * X , const int incX ) ; <nl> + <nl> + float cblas_scnrm2 ( const int N , const void * X , const int incX ) ; <nl> + float cblas_scasum ( const int N , const void * X , const int incX ) ; <nl> + <nl> + double cblas_dznrm2 ( const int N , const void * X , const int incX ) ; <nl> + double cblas_dzasum ( const int N , const void * X , const int incX ) ; <nl> + <nl> + <nl> + / * <nl> + * Functions having standard 4 prefixes ( S D C Z ) <nl> + * / <nl> + CBLAS_INDEX cblas_isamax ( const int N , const float * X , const int incX ) ; <nl> + CBLAS_INDEX cblas_idamax ( const int N , const double * X , const int incX ) ; <nl> + CBLAS_INDEX cblas_icamax ( const int N , const void * X , const int incX ) ; <nl> + CBLAS_INDEX cblas_izamax ( const int N , const void * X , const int incX ) ; <nl> + <nl> + / * <nl> + * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + * Prototypes for level 1 BLAS routines <nl> + * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + * / <nl> + <nl> + / * <nl> + * Routines with standard 4 prefixes ( s , d , c , z ) <nl> + * / <nl> + void cblas_sswap ( const int N , float * X , const int incX , <nl> + float * Y , const int incY ) ; <nl> + void cblas_scopy ( const int N , const float * X , const int incX , <nl> + float * Y , const int incY ) ; <nl> + void cblas_saxpy ( const int N , const float alpha , const float * X , <nl> + const int incX , float * Y , const int incY ) ; <nl> + <nl> + void cblas_dswap ( const int N , double * X , const int incX , <nl> + double * Y , const int incY ) ; <nl> + void cblas_dcopy ( const int N , const double * X , const int incX , <nl> + double * Y , const int incY ) ; <nl> + void cblas_daxpy ( const int N , const double alpha , const double * X , <nl> + const int incX , double * Y , const int incY ) ; <nl> + <nl> + void cblas_cswap ( const int N , void * X , const int incX , <nl> + void * Y , const int incY ) ; <nl> + void cblas_ccopy ( const int N , const void * X , const int incX , <nl> + void * Y , const int incY ) ; <nl> + void cblas_caxpy ( const int N , const void * alpha , const void * X , <nl> + const int incX , void * Y , const int incY ) ; <nl> + <nl> + void cblas_zswap ( const int N , void * X , const int incX , <nl> + void * Y , const int incY ) ; <nl> + void cblas_zcopy ( const int N , const void * X , const int incX , <nl> + void * Y , const int incY ) ; <nl> + void cblas_zaxpy ( const int N , const void * alpha , const void * X , <nl> + const int incX , void * Y , const int incY ) ; <nl> + <nl> + <nl> + / * <nl> + * Routines with S and D prefix only <nl> + * / <nl> + void cblas_srotg ( float * a , float * b , float * c , float * s ) ; <nl> + void cblas_srotmg ( float * d1 , float * d2 , float * b1 , const float b2 , float * P ) ; <nl> + void cblas_srot ( const int N , float * X , const int incX , <nl> + float * Y , const int incY , const float c , const float s ) ; <nl> + void cblas_srotm ( const int N , float * X , const int incX , <nl> + float * Y , const int incY , const float * P ) ; <nl> + <nl> + void cblas_drotg ( double * a , double * b , double * c , double * s ) ; <nl> + void cblas_drotmg ( double * d1 , double * d2 , double * b1 , const double b2 , double * P ) ; <nl> + void cblas_drot ( const int N , double * X , const int incX , <nl> + double * Y , const int incY , const double c , const double s ) ; <nl> + void cblas_drotm ( const int N , double * X , const int incX , <nl> + double * Y , const int incY , const double * P ) ; <nl> + <nl> + <nl> + / * <nl> + * Routines with S D C Z CS and ZD prefixes <nl> + * / <nl> + void cblas_sscal ( const int N , const float alpha , float * X , const int incX ) ; <nl> + void cblas_dscal ( const int N , const double alpha , double * X , const int incX ) ; <nl> + void cblas_cscal ( const int N , const void * alpha , void * X , const int incX ) ; <nl> + void cblas_zscal ( const int N , const void * alpha , void * X , const int incX ) ; <nl> + void cblas_csscal ( const int N , const float alpha , void * X , const int incX ) ; <nl> + void cblas_zdscal ( const int N , const double alpha , void * X , const int incX ) ; <nl> + <nl> + / * <nl> + * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + * Prototypes for level 2 BLAS <nl> + * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + * / <nl> + <nl> + / * <nl> + * Routines with standard 4 prefixes ( S , D , C , Z ) <nl> + * / <nl> + void cblas_sgemv ( const enum CBLAS_ORDER order , <nl> + const enum CBLAS_TRANSPOSE TransA , const int M , const int N , <nl> + const float alpha , const float * A , const int lda , <nl> + const float * X , const int incX , const float beta , <nl> + float * Y , const int incY ) ; <nl> + void cblas_sgbmv ( const enum CBLAS_ORDER order , <nl> + const enum CBLAS_TRANSPOSE TransA , const int M , const int N , <nl> + const int KL , const int KU , const float alpha , <nl> + const float * A , const int lda , const float * X , <nl> + const int incX , const float beta , float * Y , const int incY ) ; <nl> + void cblas_strmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const float * A , const int lda , <nl> + float * X , const int incX ) ; <nl> + void cblas_stbmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const int K , const float * A , const int lda , <nl> + float * X , const int incX ) ; <nl> + void cblas_stpmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const float * Ap , float * X , const int incX ) ; <nl> + void cblas_strsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const float * A , const int lda , float * X , <nl> + const int incX ) ; <nl> + void cblas_stbsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const int K , const float * A , const int lda , <nl> + float * X , const int incX ) ; <nl> + void cblas_stpsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const float * Ap , float * X , const int incX ) ; <nl> + <nl> + void cblas_dgemv ( const enum CBLAS_ORDER order , <nl> + const enum CBLAS_TRANSPOSE TransA , const int M , const int N , <nl> + const double alpha , const double * A , const int lda , <nl> + const double * X , const int incX , const double beta , <nl> + double * Y , const int incY ) ; <nl> + void cblas_dgbmv ( const enum CBLAS_ORDER order , <nl> + const enum CBLAS_TRANSPOSE TransA , const int M , const int N , <nl> + const int KL , const int KU , const double alpha , <nl> + const double * A , const int lda , const double * X , <nl> + const int incX , const double beta , double * Y , const int incY ) ; <nl> + void cblas_dtrmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const double * A , const int lda , <nl> + double * X , const int incX ) ; <nl> + void cblas_dtbmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const int K , const double * A , const int lda , <nl> + double * X , const int incX ) ; <nl> + void cblas_dtpmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const double * Ap , double * X , const int incX ) ; <nl> + void cblas_dtrsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const double * A , const int lda , double * X , <nl> + const int incX ) ; <nl> + void cblas_dtbsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const int K , const double * A , const int lda , <nl> + double * X , const int incX ) ; <nl> + void cblas_dtpsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const double * Ap , double * X , const int incX ) ; <nl> + <nl> + void cblas_cgemv ( const enum CBLAS_ORDER order , <nl> + const enum CBLAS_TRANSPOSE TransA , const int M , const int N , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * X , const int incX , const void * beta , <nl> + void * Y , const int incY ) ; <nl> + void cblas_cgbmv ( const enum CBLAS_ORDER order , <nl> + const enum CBLAS_TRANSPOSE TransA , const int M , const int N , <nl> + const int KL , const int KU , const void * alpha , <nl> + const void * A , const int lda , const void * X , <nl> + const int incX , const void * beta , void * Y , const int incY ) ; <nl> + void cblas_ctrmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const void * A , const int lda , <nl> + void * X , const int incX ) ; <nl> + void cblas_ctbmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const int K , const void * A , const int lda , <nl> + void * X , const int incX ) ; <nl> + void cblas_ctpmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const void * Ap , void * X , const int incX ) ; <nl> + void cblas_ctrsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const void * A , const int lda , void * X , <nl> + const int incX ) ; <nl> + void cblas_ctbsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const int K , const void * A , const int lda , <nl> + void * X , const int incX ) ; <nl> + void cblas_ctpsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const void * Ap , void * X , const int incX ) ; <nl> + <nl> + void cblas_zgemv ( const enum CBLAS_ORDER order , <nl> + const enum CBLAS_TRANSPOSE TransA , const int M , const int N , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * X , const int incX , const void * beta , <nl> + void * Y , const int incY ) ; <nl> + void cblas_zgbmv ( const enum CBLAS_ORDER order , <nl> + const enum CBLAS_TRANSPOSE TransA , const int M , const int N , <nl> + const int KL , const int KU , const void * alpha , <nl> + const void * A , const int lda , const void * X , <nl> + const int incX , const void * beta , void * Y , const int incY ) ; <nl> + void cblas_ztrmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const void * A , const int lda , <nl> + void * X , const int incX ) ; <nl> + void cblas_ztbmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const int K , const void * A , const int lda , <nl> + void * X , const int incX ) ; <nl> + void cblas_ztpmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const void * Ap , void * X , const int incX ) ; <nl> + void cblas_ztrsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const void * A , const int lda , void * X , <nl> + const int incX ) ; <nl> + void cblas_ztbsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const int K , const void * A , const int lda , <nl> + void * X , const int incX ) ; <nl> + void cblas_ztpsv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE TransA , const enum CBLAS_DIAG Diag , <nl> + const int N , const void * Ap , void * X , const int incX ) ; <nl> + <nl> + <nl> + / * <nl> + * Routines with S and D prefixes only <nl> + * / <nl> + void cblas_ssymv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const float alpha , const float * A , <nl> + const int lda , const float * X , const int incX , <nl> + const float beta , float * Y , const int incY ) ; <nl> + void cblas_ssbmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const int K , const float alpha , const float * A , <nl> + const int lda , const float * X , const int incX , <nl> + const float beta , float * Y , const int incY ) ; <nl> + void cblas_sspmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const float alpha , const float * Ap , <nl> + const float * X , const int incX , <nl> + const float beta , float * Y , const int incY ) ; <nl> + void cblas_sger ( const enum CBLAS_ORDER order , const int M , const int N , <nl> + const float alpha , const float * X , const int incX , <nl> + const float * Y , const int incY , float * A , const int lda ) ; <nl> + void cblas_ssyr ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const float alpha , const float * X , <nl> + const int incX , float * A , const int lda ) ; <nl> + void cblas_sspr ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const float alpha , const float * X , <nl> + const int incX , float * Ap ) ; <nl> + void cblas_ssyr2 ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const float alpha , const float * X , <nl> + const int incX , const float * Y , const int incY , float * A , <nl> + const int lda ) ; <nl> + void cblas_sspr2 ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const float alpha , const float * X , <nl> + const int incX , const float * Y , const int incY , float * A ) ; <nl> + <nl> + void cblas_dsymv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const double alpha , const double * A , <nl> + const int lda , const double * X , const int incX , <nl> + const double beta , double * Y , const int incY ) ; <nl> + void cblas_dsbmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const int K , const double alpha , const double * A , <nl> + const int lda , const double * X , const int incX , <nl> + const double beta , double * Y , const int incY ) ; <nl> + void cblas_dspmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const double alpha , const double * Ap , <nl> + const double * X , const int incX , <nl> + const double beta , double * Y , const int incY ) ; <nl> + void cblas_dger ( const enum CBLAS_ORDER order , const int M , const int N , <nl> + const double alpha , const double * X , const int incX , <nl> + const double * Y , const int incY , double * A , const int lda ) ; <nl> + void cblas_dsyr ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const double alpha , const double * X , <nl> + const int incX , double * A , const int lda ) ; <nl> + void cblas_dspr ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const double alpha , const double * X , <nl> + const int incX , double * Ap ) ; <nl> + void cblas_dsyr2 ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const double alpha , const double * X , <nl> + const int incX , const double * Y , const int incY , double * A , <nl> + const int lda ) ; <nl> + void cblas_dspr2 ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const double alpha , const double * X , <nl> + const int incX , const double * Y , const int incY , double * A ) ; <nl> + <nl> + <nl> + / * <nl> + * Routines with C and Z prefixes only <nl> + * / <nl> + void cblas_chemv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const void * alpha , const void * A , <nl> + const int lda , const void * X , const int incX , <nl> + const void * beta , void * Y , const int incY ) ; <nl> + void cblas_chbmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const int K , const void * alpha , const void * A , <nl> + const int lda , const void * X , const int incX , <nl> + const void * beta , void * Y , const int incY ) ; <nl> + void cblas_chpmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const void * alpha , const void * Ap , <nl> + const void * X , const int incX , <nl> + const void * beta , void * Y , const int incY ) ; <nl> + void cblas_cgeru ( const enum CBLAS_ORDER order , const int M , const int N , <nl> + const void * alpha , const void * X , const int incX , <nl> + const void * Y , const int incY , void * A , const int lda ) ; <nl> + void cblas_cgerc ( const enum CBLAS_ORDER order , const int M , const int N , <nl> + const void * alpha , const void * X , const int incX , <nl> + const void * Y , const int incY , void * A , const int lda ) ; <nl> + void cblas_cher ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const float alpha , const void * X , const int incX , <nl> + void * A , const int lda ) ; <nl> + void cblas_chpr ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const float alpha , const void * X , <nl> + const int incX , void * A ) ; <nl> + void cblas_cher2 ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , const int N , <nl> + const void * alpha , const void * X , const int incX , <nl> + const void * Y , const int incY , void * A , const int lda ) ; <nl> + void cblas_chpr2 ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , const int N , <nl> + const void * alpha , const void * X , const int incX , <nl> + const void * Y , const int incY , void * Ap ) ; <nl> + <nl> + void cblas_zhemv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const void * alpha , const void * A , <nl> + const int lda , const void * X , const int incX , <nl> + const void * beta , void * Y , const int incY ) ; <nl> + void cblas_zhbmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const int K , const void * alpha , const void * A , <nl> + const int lda , const void * X , const int incX , <nl> + const void * beta , void * Y , const int incY ) ; <nl> + void cblas_zhpmv ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const void * alpha , const void * Ap , <nl> + const void * X , const int incX , <nl> + const void * beta , void * Y , const int incY ) ; <nl> + void cblas_zgeru ( const enum CBLAS_ORDER order , const int M , const int N , <nl> + const void * alpha , const void * X , const int incX , <nl> + const void * Y , const int incY , void * A , const int lda ) ; <nl> + void cblas_zgerc ( const enum CBLAS_ORDER order , const int M , const int N , <nl> + const void * alpha , const void * X , const int incX , <nl> + const void * Y , const int incY , void * A , const int lda ) ; <nl> + void cblas_zher ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const double alpha , const void * X , const int incX , <nl> + void * A , const int lda ) ; <nl> + void cblas_zhpr ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , <nl> + const int N , const double alpha , const void * X , <nl> + const int incX , void * A ) ; <nl> + void cblas_zher2 ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , const int N , <nl> + const void * alpha , const void * X , const int incX , <nl> + const void * Y , const int incY , void * A , const int lda ) ; <nl> + void cblas_zhpr2 ( const enum CBLAS_ORDER order , const enum CBLAS_UPLO Uplo , const int N , <nl> + const void * alpha , const void * X , const int incX , <nl> + const void * Y , const int incY , void * Ap ) ; <nl> + <nl> + / * <nl> + * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + * Prototypes for level 3 BLAS <nl> + * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + * / <nl> + <nl> + / * <nl> + * Routines with standard 4 prefixes ( S , D , C , Z ) <nl> + * / <nl> + void cblas_sgemm ( const enum CBLAS_ORDER Order , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_TRANSPOSE TransB , const int M , const int N , <nl> + const int K , const float alpha , const float * A , <nl> + const int lda , const float * B , const int ldb , <nl> + const float beta , float * C , const int ldc ) ; <nl> + void cblas_ssymm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const int M , const int N , <nl> + const float alpha , const float * A , const int lda , <nl> + const float * B , const int ldb , const float beta , <nl> + float * C , const int ldc ) ; <nl> + void cblas_ssyrk ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const float alpha , const float * A , const int lda , <nl> + const float beta , float * C , const int ldc ) ; <nl> + void cblas_ssyr2k ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const float alpha , const float * A , const int lda , <nl> + const float * B , const int ldb , const float beta , <nl> + float * C , const int ldc ) ; <nl> + void cblas_strmm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_DIAG Diag , const int M , const int N , <nl> + const float alpha , const float * A , const int lda , <nl> + float * B , const int ldb ) ; <nl> + void cblas_strsm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_DIAG Diag , const int M , const int N , <nl> + const float alpha , const float * A , const int lda , <nl> + float * B , const int ldb ) ; <nl> + <nl> + void cblas_dgemm ( const enum CBLAS_ORDER Order , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_TRANSPOSE TransB , const int M , const int N , <nl> + const int K , const double alpha , const double * A , <nl> + const int lda , const double * B , const int ldb , <nl> + const double beta , double * C , const int ldc ) ; <nl> + void cblas_dsymm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const int M , const int N , <nl> + const double alpha , const double * A , const int lda , <nl> + const double * B , const int ldb , const double beta , <nl> + double * C , const int ldc ) ; <nl> + void cblas_dsyrk ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const double alpha , const double * A , const int lda , <nl> + const double beta , double * C , const int ldc ) ; <nl> + void cblas_dsyr2k ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const double alpha , const double * A , const int lda , <nl> + const double * B , const int ldb , const double beta , <nl> + double * C , const int ldc ) ; <nl> + void cblas_dtrmm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_DIAG Diag , const int M , const int N , <nl> + const double alpha , const double * A , const int lda , <nl> + double * B , const int ldb ) ; <nl> + void cblas_dtrsm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_DIAG Diag , const int M , const int N , <nl> + const double alpha , const double * A , const int lda , <nl> + double * B , const int ldb ) ; <nl> + <nl> + void cblas_cgemm ( const enum CBLAS_ORDER Order , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_TRANSPOSE TransB , const int M , const int N , <nl> + const int K , const void * alpha , const void * A , <nl> + const int lda , const void * B , const int ldb , <nl> + const void * beta , void * C , const int ldc ) ; <nl> + void cblas_csymm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const int M , const int N , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * B , const int ldb , const void * beta , <nl> + void * C , const int ldc ) ; <nl> + void cblas_csyrk ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * beta , void * C , const int ldc ) ; <nl> + void cblas_csyr2k ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * B , const int ldb , const void * beta , <nl> + void * C , const int ldc ) ; <nl> + void cblas_ctrmm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_DIAG Diag , const int M , const int N , <nl> + const void * alpha , const void * A , const int lda , <nl> + void * B , const int ldb ) ; <nl> + void cblas_ctrsm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_DIAG Diag , const int M , const int N , <nl> + const void * alpha , const void * A , const int lda , <nl> + void * B , const int ldb ) ; <nl> + <nl> + void cblas_zgemm ( const enum CBLAS_ORDER Order , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_TRANSPOSE TransB , const int M , const int N , <nl> + const int K , const void * alpha , const void * A , <nl> + const int lda , const void * B , const int ldb , <nl> + const void * beta , void * C , const int ldc ) ; <nl> + void cblas_zsymm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const int M , const int N , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * B , const int ldb , const void * beta , <nl> + void * C , const int ldc ) ; <nl> + void cblas_zsyrk ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * beta , void * C , const int ldc ) ; <nl> + void cblas_zsyr2k ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * B , const int ldb , const void * beta , <nl> + void * C , const int ldc ) ; <nl> + void cblas_ztrmm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_DIAG Diag , const int M , const int N , <nl> + const void * alpha , const void * A , const int lda , <nl> + void * B , const int ldb ) ; <nl> + void cblas_ztrsm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const enum CBLAS_TRANSPOSE TransA , <nl> + const enum CBLAS_DIAG Diag , const int M , const int N , <nl> + const void * alpha , const void * A , const int lda , <nl> + void * B , const int ldb ) ; <nl> + <nl> + <nl> + / * <nl> + * Routines with prefixes C and Z only <nl> + * / <nl> + void cblas_chemm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const int M , const int N , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * B , const int ldb , const void * beta , <nl> + void * C , const int ldc ) ; <nl> + void cblas_cherk ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const float alpha , const void * A , const int lda , <nl> + const float beta , void * C , const int ldc ) ; <nl> + void cblas_cher2k ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * B , const int ldb , const float beta , <nl> + void * C , const int ldc ) ; <nl> + <nl> + void cblas_zhemm ( const enum CBLAS_ORDER Order , const enum CBLAS_SIDE Side , <nl> + const enum CBLAS_UPLO Uplo , const int M , const int N , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * B , const int ldb , const void * beta , <nl> + void * C , const int ldc ) ; <nl> + void cblas_zherk ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const double alpha , const void * A , const int lda , <nl> + const double beta , void * C , const int ldc ) ; <nl> + void cblas_zher2k ( const enum CBLAS_ORDER Order , const enum CBLAS_UPLO Uplo , <nl> + const enum CBLAS_TRANSPOSE Trans , const int N , const int K , <nl> + const void * alpha , const void * A , const int lda , <nl> + const void * B , const int ldb , const double beta , <nl> + void * C , const int ldc ) ; <nl> + <nl> + void cblas_xerbla ( int p , const char * rout , const char * form , . . . ) ; <nl> + <nl> + # ifdef __cplusplus <nl> + } <nl> + # endif <nl> + <nl> + # endif <nl>
Bundle generic cblas . h header for users that don ' t have libblas - dev installed already
apache/incubator-mxnet
7be95f60df18f13ebb8557c1d2977030035022ca
2016-04-18T19:28:39Z
mmm a / python / caffe / imagenet / power_wrapper . py <nl> ppp b / python / caffe / imagenet / power_wrapper . py <nl> def assemble_batches ( image_fnames , crop_mode = ' center_only ' , batch_size = 10 ) : <nl> Column ' image ' contains ( X x 3 x 227 x 227 ) ndarrays . <nl> Column ' filename ' contains source filenames . <nl> If ' filename ' is None , then the row is just for padding . <nl> + <nl> + Note : for increased efficiency , increase the batch size ( to the limit of gpu <nl> + memory ) to avoid the communication cost <nl> " " " <nl> if crop_mode = = ' center_only ' : <nl> images_df = _assemble_images_center_only ( image_fnames ) <nl>
give batch size efficiency advice
BVLC/caffe
eafd6950bcae88e76d5f2aa97c09450f23e36138
2014-01-24T06:31:29Z
mmm a / tests / queries / 0_stateless / 01302_aggregate_state_exception_memory_leak . sh <nl> ppp b / tests / queries / 0_stateless / 01302_aggregate_state_exception_memory_leak . sh <nl> CURDIR = $ ( cd " $ ( dirname " $ { BASH_SOURCE [ 0 ] } " ) " & & pwd ) <nl> <nl> function test ( ) <nl> { <nl> - for i in { 1 . . 50 } ; do <nl> - $ CLICKHOUSE_CLIENT - - query " SELECT groupArrayIfState ( ( ' Hello , world ' AS s ) | | s | | s | | s | | s | | s | | s | | s | | s | | s , NOT throwIf ( number > 50000000 , ' Ok ' ) ) FROM system . numbers_mt GROUP BY number % 10 " ; <nl> + for i in { 1 . . 250 } ; do <nl> + $ CLICKHOUSE_CLIENT - - query " SELECT groupArrayIfState ( ( ' Hello , world ' AS s ) | | s | | s | | s | | s | | s | | s | | s | | s | | s , NOT throwIf ( number > 10000000 , ' Ok ' ) ) FROM system . numbers_mt GROUP BY number % 10 " ; <nl> done <nl> } <nl> <nl> export - f test ; <nl> <nl> # If the memory leak exists , it will lead to OOM fairly quickly . <nl> - timeout 10 bash - c test 2 > & 1 | grep - o - F ' Ok ' | uniq <nl> + timeout 30 bash - c test 2 > & 1 | grep - o - F ' Ok ' | uniq <nl>
Changed timeouts in test
ClickHouse/ClickHouse
7ba2d7e15f64838d092ae50931be6d362e5d6b8b
2020-06-08T12:35:57Z
mmm a / cocos2dx / platform / android / java / src / org / cocos2dx / lib / Cocos2dxHelper . java <nl> ppp b / cocos2dx / platform / android / java / src / org / cocos2dx / lib / Cocos2dxHelper . java <nl> of this software and associated documentation files ( the " Software " ) , to deal <nl> private static Cocos2dxMusic sCocos2dMusic ; <nl> private static Cocos2dxSound sCocos2dSound ; <nl> private static AssetManager sAssetManager ; <nl> - private static Cocos2dxAccelerometer sCocos2dxAccelerometer ; <nl> private static boolean sAccelerometerEnabled ; <nl> private static String sPackageName ; <nl> private static String sFileDirectory ; <nl> - private static Context sContext = null ; <nl> + private static Activity sActivity = null ; <nl> private static Cocos2dxHelperListener sCocos2dxHelperListener ; <nl> <nl> / * * <nl> of this software and associated documentation files ( the " Software " ) , to deal <nl> public static void init ( final Activity activity ) { <nl> final ApplicationInfo applicationInfo = activity . getApplicationInfo ( ) ; <nl> <nl> - Cocos2dxHelper . sContext = activity ; <nl> + Cocos2dxHelper . sActivity = activity ; <nl> <nl> try { <nl> / / Get the lib_name from AndroidManifest . xml metadata <nl> public static void init ( final Activity activity ) { <nl> Cocos2dxHelper . sFileDirectory = activity . getFilesDir ( ) . getAbsolutePath ( ) ; <nl> / / Cocos2dxHelper . nativeSetApkPath ( applicationInfo . sourceDir ) ; <nl> <nl> - Cocos2dxHelper . sCocos2dxAccelerometer = new Cocos2dxAccelerometer ( activity ) ; <nl> Cocos2dxHelper . sCocos2dMusic = new Cocos2dxMusic ( activity ) ; <nl> Cocos2dxHelper . sCocos2dSound = new Cocos2dxSound ( activity ) ; <nl> Cocos2dxHelper . sAssetManager = activity . getAssets ( ) ; <nl> public static void init ( final Activity activity ) { <nl> Cocos2dxETCLoader . setContext ( activity ) ; <nl> } <nl> <nl> + public static Activity getActivity ( ) { <nl> + return sActivity ; <nl> + } <nl> + <nl> / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / Getter & Setter <nl> / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> public static AssetManager getAssetManager ( ) { <nl> return Cocos2dxHelper . sAssetManager ; <nl> } <nl> <nl> - public static void enableAccelerometer ( ) { <nl> - Cocos2dxHelper . sAccelerometerEnabled = true ; <nl> - Cocos2dxHelper . sCocos2dxAccelerometer . enable ( ) ; <nl> - } <nl> - <nl> - <nl> - public static void setAccelerometerInterval ( float interval ) { <nl> - Cocos2dxHelper . sCocos2dxAccelerometer . setInterval ( interval ) ; <nl> - } <nl> - <nl> - public static void disableAccelerometer ( ) { <nl> - Cocos2dxHelper . sAccelerometerEnabled = false ; <nl> - Cocos2dxHelper . sCocos2dxAccelerometer . disable ( ) ; <nl> - } <nl> - <nl> public static void preloadBackgroundMusic ( final String pPath ) { <nl> Cocos2dxHelper . sCocos2dMusic . preloadBackgroundMusic ( pPath ) ; <nl> } <nl> public static void end ( ) { <nl> Cocos2dxHelper . sCocos2dSound . end ( ) ; <nl> } <nl> <nl> - public static void onResume ( ) { <nl> - if ( Cocos2dxHelper . sAccelerometerEnabled ) { <nl> - Cocos2dxHelper . sCocos2dxAccelerometer . enable ( ) ; <nl> - } <nl> - } <nl> - <nl> - public static void onPause ( ) { <nl> - if ( Cocos2dxHelper . sAccelerometerEnabled ) { <nl> - Cocos2dxHelper . sCocos2dxAccelerometer . disable ( ) ; <nl> - } <nl> - } <nl> - <nl> public static void terminateProcess ( ) { <nl> android . os . Process . killProcess ( android . os . Process . myPid ( ) ) ; <nl> } <nl> public void run ( ) { <nl> <nl> public static int getDPI ( ) <nl> { <nl> - if ( sContext ! = null ) <nl> + if ( sActivity ! = null ) <nl> { <nl> DisplayMetrics metrics = new DisplayMetrics ( ) ; <nl> - WindowManager wm = ( ( Activity ) sContext ) . getWindowManager ( ) ; <nl> + WindowManager wm = sActivity . getWindowManager ( ) ; <nl> if ( wm ! = null ) <nl> { <nl> Display d = wm . getDefaultDisplay ( ) ; <nl> public static int getDPI ( ) <nl> / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> public static boolean getBoolForKey ( String key , boolean defaultValue ) { <nl> - SharedPreferences settings = ( ( Activity ) sContext ) . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> + SharedPreferences settings = sActivity . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> return settings . getBoolean ( key , defaultValue ) ; <nl> } <nl> <nl> public static int getIntegerForKey ( String key , int defaultValue ) { <nl> - SharedPreferences settings = ( ( Activity ) sContext ) . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> + SharedPreferences settings = sActivity . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> return settings . getInt ( key , defaultValue ) ; <nl> } <nl> <nl> public static float getFloatForKey ( String key , float defaultValue ) { <nl> - SharedPreferences settings = ( ( Activity ) sContext ) . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> + SharedPreferences settings = sActivity . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> return settings . getFloat ( key , defaultValue ) ; <nl> } <nl> <nl> public static double getDoubleForKey ( String key , double defaultValue ) { <nl> / / SharedPreferences doesn ' t support saving double value <nl> - SharedPreferences settings = ( ( Activity ) sContext ) . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> + SharedPreferences settings = sActivity . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> return settings . getFloat ( key , ( float ) defaultValue ) ; <nl> } <nl> <nl> public static String getStringForKey ( String key , String defaultValue ) { <nl> - SharedPreferences settings = ( ( Activity ) sContext ) . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> + SharedPreferences settings = sActivity . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> return settings . getString ( key , defaultValue ) ; <nl> } <nl> <nl> public static void setBoolForKey ( String key , boolean value ) { <nl> - SharedPreferences settings = ( ( Activity ) sContext ) . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> + SharedPreferences settings = sActivity . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> SharedPreferences . Editor editor = settings . edit ( ) ; <nl> editor . putBoolean ( key , value ) ; <nl> editor . commit ( ) ; <nl> } <nl> <nl> public static void setIntegerForKey ( String key , int value ) { <nl> - SharedPreferences settings = ( ( Activity ) sContext ) . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> + SharedPreferences settings = sActivity . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> SharedPreferences . Editor editor = settings . edit ( ) ; <nl> editor . putInt ( key , value ) ; <nl> editor . commit ( ) ; <nl> } <nl> <nl> public static void setFloatForKey ( String key , float value ) { <nl> - SharedPreferences settings = ( ( Activity ) sContext ) . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> + SharedPreferences settings = sActivity . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> SharedPreferences . Editor editor = settings . edit ( ) ; <nl> editor . putFloat ( key , value ) ; <nl> editor . commit ( ) ; <nl> public static void setFloatForKey ( String key , float value ) { <nl> <nl> public static void setDoubleForKey ( String key , double value ) { <nl> / / SharedPreferences doesn ' t support recording double value <nl> - SharedPreferences settings = ( ( Activity ) sContext ) . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> + SharedPreferences settings = sActivity . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> SharedPreferences . Editor editor = settings . edit ( ) ; <nl> editor . putFloat ( key , ( float ) value ) ; <nl> editor . commit ( ) ; <nl> } <nl> <nl> public static void setStringForKey ( String key , String value ) { <nl> - SharedPreferences settings = ( ( Activity ) sContext ) . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> + SharedPreferences settings = sActivity . getSharedPreferences ( Cocos2dxHelper . PREFS_NAME , 0 ) ; <nl> SharedPreferences . Editor editor = settings . edit ( ) ; <nl> editor . putString ( key , value ) ; <nl> editor . commit ( ) ; <nl> mmm a / cocos2dx / platform / android / java / src / org / cocos2dx / lib / Cocos2dxLocalStorage . java <nl> ppp b / cocos2dx / platform / android / java / src / org / cocos2dx / lib / Cocos2dxLocalStorage . java <nl> of this software and associated documentation files ( the " Software " ) , to deal <nl> * @ return <nl> * / <nl> public static boolean init ( String dbName , String tableName ) { <nl> - if ( Cocos2dxActivity . getContext ( ) ! = null ) { <nl> + if ( Cocos2dxHelper . getActivity ( ) ! = null ) { <nl> DATABASE_NAME = dbName ; <nl> TABLE_NAME = tableName ; <nl> - mDatabaseOpenHelper = new DBOpenHelper ( Cocos2dxActivity . getContext ( ) ) ; <nl> + mDatabaseOpenHelper = new DBOpenHelper ( Cocos2dxHelper . getActivity ( ) ) ; <nl> mDatabase = mDatabaseOpenHelper . getWritableDatabase ( ) ; <nl> return true ; <nl> } <nl>
Helper and LocalStorage now use NativeActivity directly
cocos2d/cocos2d-x
4567ab96b85fa68cad2cf3e5a374f79e217ed1ea
2013-08-05T09:05:42Z
mmm a / tensorflow / python / distribute / input_lib . py <nl> ppp b / tensorflow / python / distribute / input_lib . py <nl> def __init__ ( self , dataset = None , worker = None , devices = None , components = None , <nl> else : <nl> if ( components is not None or element_spec is not None ) : <nl> raise ValueError ( error_message ) <nl> - super ( _SingleWorkerOwnedDatasetIterator , self ) . __init__ ( dataset = dataset , <nl> - worker = worker , <nl> - devices = devices ) <nl> + super ( _SingleWorkerOwnedDatasetIterator , self ) . __init__ ( dataset , worker , <nl> + devices ) <nl> <nl> def _make_iterator ( self ) : <nl> " " " Make appropriate iterator on the dataset . " " " <nl> def _make_iterator ( self ) : <nl> raise ValueError ( " Worked device must be specified when creating an " <nl> " owned iterator . " ) <nl> if ( self . _options is None <nl> - or self . _options . experimental_replication_mode = = InputReplicationMode . PER_WORKER ) : <nl> + or self . _options . experimental_replication_mode = = InputReplicationMode . PER_WORKER <nl> + or ( self . _options . experimental_replication_mode = = InputReplicationMode . PER_REPLICA <nl> + and self . _options . experimental_prefetch_to_device ) ) : <nl> host_device = device_util . get_host_for_device ( self . _worker ) <nl> with ops . device ( self . _worker ) : <nl> self . _iterator = multi_device_iterator_ops . OwnedMultiDeviceIterator ( <nl> self . _dataset , self . _devices , source_device = host_device ) <nl> else : <nl> - worker_device = self . _worker <nl> - if self . _options . experimental_prefetch_to_device : <nl> - raise ValueError ( " ` experimental_prefetch_to_device ` is not supported together with " <nl> - " ` InputReplicationMode . PER_REPLICA ` " ) <nl> - else : <nl> - with ops . device ( worker_device ) : <nl> - self . _iterator = iter ( self . _dataset ) <nl> + with ops . device ( self . _worker ) : <nl> + self . _iterator = iter ( self . _dataset ) <nl> <nl> @ property <nl> def element_spec ( self ) : <nl> mmm a / tensorflow / python / distribute / input_lib_test . py <nl> ppp b / tensorflow / python / distribute / input_lib_test . py <nl> def sum_while_loop ( ds ) : <nl> self . assertAllEqual ( nest . flatten ( sums ) , [ expected_for_sum ] * 3 ) <nl> <nl> <nl> - class DistributedIteratorPerReplicaTest ( test . TestCase , parameterized . TestCase ) : <nl> + class DistributedIteratorPerDeviceTest ( DistributedIteratorTestBase , parameterized . TestCase ) : <nl> + " " " Tests for PER_WORKER and PER_REPLICA ' s InputOptions variants . " " " <nl> + <nl> + def setUp ( self ) : <nl> + context . _reset_context ( ) <nl> + strategy_combinations . set_virtual_cpus_to_at_least ( 3 ) <nl> + super ( DistributedIteratorPerDeviceTest , self ) . setUp ( ) <nl> <nl> @ combinations . generate ( <nl> combinations . combine ( <nl> + input_options = [ <nl> + distribute_lib . InputOptions ( <nl> + experimental_place_dataset_on_device = False , <nl> + experimental_prefetch_to_device = True , <nl> + experimental_replication_mode = distribute_lib . InputReplicationMode . PER_WORKER ) , <nl> + distribute_lib . InputOptions ( <nl> + experimental_place_dataset_on_device = False , <nl> + experimental_prefetch_to_device = True , <nl> + experimental_replication_mode = distribute_lib . InputReplicationMode . PER_REPLICA ) , <nl> + ] , <nl> mode = [ " eager " ] , <nl> distribution = [ <nl> strategy_combinations . mirrored_strategy_with_two_gpus , <nl> strategy_combinations . mirrored_strategy_with_cpu_1_and_2 , <nl> strategy_combinations . mirrored_strategy_with_gpu_and_cpu , <nl> - ] ) ) <nl> - <nl> - def setUp ( self ) : <nl> - super ( DistributedIteratorPerReplicaTest , self ) . setUp ( ) <nl> - strategy_combinations . set_virtual_cpus_to_at_least ( 3 ) <nl> - <nl> - def testInputSignatureForPerReplicaValues ( self , distribution ) : <nl> + ] ) ) <nl> + def testInputSignatureForPerWorkerValuesWithPrefetch ( self , distribution , input_options ) : <nl> def dataset_fn ( input_context ) : <nl> - return tf . data . Dataset . from_tensor_slices ( <nl> - np . array ( np . arange ( 0 , 16 ) ) . reshape ( 4 , 4 ) ) <nl> - <nl> - input_options = tf . distribute . InputOptions ( <nl> - replication_mode = tf . distribute . InputReplicationMode . PER_REPLICA ) <nl> + return dataset_ops . Dataset . from_tensor_slices ( <nl> + [ 1 , 2 , 3 ] ) <nl> <nl> ds = distribution . experimental_distribute_datasets_from_function ( <nl> dataset_fn , input_options ) <nl> <nl> - iterator = iter ( ds ) <nl> - type_spec = iterator . element_spec <nl> + for x in ds : <nl> + assert x . values [ 0 ] . device = = distribution . extended . worker_devices [ 0 ] <nl> + assert x . values [ 0 ] . backing_device = = distribution . extended . worker_devices [ 0 ] <nl> + assert x . values [ 1 ] . device = = distribution . extended . worker_devices [ 1 ] <nl> + assert x . values [ 1 ] . backing_device = = distribution . extended . worker_devices [ 1 ] <nl> + <nl> + @ combinations . generate ( <nl> + combinations . combine ( <nl> + distribution = [ <nl> + strategy_combinations . mirrored_strategy_with_two_gpus , <nl> + strategy_combinations . mirrored_strategy_with_cpu_1_and_2 , <nl> + strategy_combinations . mirrored_strategy_with_gpu_and_cpu , <nl> + ] , <nl> + input_options = [ <nl> + distribute_lib . InputOptions ( <nl> + experimental_place_dataset_on_device = False , <nl> + experimental_prefetch_to_device = False , <nl> + experimental_replication_mode = distribute_lib . InputReplicationMode . PER_WORKER ) <nl> + ] , <nl> + mode = [ " eager " ] , ) ) <nl> + def testInputSignatureForPerWorkerValuesWithoutPrefetch ( self , distribution , input_options ) : <nl> + def dataset_fn ( input_context ) : <nl> + return dataset_ops . Dataset . from_tensor_slices ( <nl> + np . full ( 4 , input_context . input_pipeline_id ) ) <nl> <nl> - @ def_function . function ( input_signature = [ type_spec ] ) <nl> - def process_inputs ( inputs ) : <nl> - distribution . run ( lambda inputs : inputs , args = ( inputs , ) ) <nl> + ds = distribution . experimental_distribute_datasets_from_function ( <nl> + dataset_fn , input_options ) <nl> <nl> for x in ds : <nl> - process_inputs ( x ) <nl> - self . assertEqual ( <nl> - x . values [ 0 ] . device , <nl> - distribution . extended . worker_devices [ 0 ] ) <nl> - self . assertEqual ( <nl> - x . values [ 0 ] . backing_device , <nl> - distribution . extended . worker_devices [ 0 ] ) <nl> - self . assertEqual ( <nl> - x . values [ 1 ] . device , <nl> - distribution . extended . worker_devices [ 1 ] ) <nl> - self . assertEqual ( <nl> - x . values [ 1 ] . backing_device , <nl> - distribution . extended . worker_devices [ 1 ] ) <nl> - break <nl> + x = distribution . run ( lambda inputs : inputs , args = ( x , ) ) <nl> + assert x . values [ 0 ] . device = = ' / job : localhost / replica : 0 / task : 0 / device : CPU : 0 ' <nl> + assert x . values [ 0 ] . backing_device = = ' / job : localhost / replica : 0 / task : 0 / device : CPU : 0 ' <nl> + assert x . values [ 1 ] . device = = ' / job : localhost / replica : 0 / task : 0 / device : CPU : 0 ' <nl> + assert x . values [ 1 ] . backing_device = = ' / job : localhost / replica : 0 / task : 0 / device : CPU : 0 ' <nl> + <nl> + @ combinations . generate ( <nl> + combinations . combine ( <nl> + input_options = [ distribute_lib . InputOptions ( <nl> + experimental_place_dataset_on_device = True , <nl> + experimental_prefetch_to_device = False , <nl> + experimental_replication_mode = distribute_lib . InputReplicationMode . PER_WORKER ) , <nl> + distribute_lib . InputOptions ( <nl> + experimental_place_dataset_on_device = True , <nl> + experimental_prefetch_to_device = True , <nl> + experimental_replication_mode = distribute_lib . InputReplicationMode . PER_REPLICA ) ] , <nl> + mode = [ " eager " ] , <nl> + distribution = [ <nl> + strategy_combinations . mirrored_strategy_with_two_gpus , <nl> + strategy_combinations . mirrored_strategy_with_cpu_1_and_2 , <nl> + strategy_combinations . mirrored_strategy_with_gpu_and_cpu , <nl> + ] ) ) <nl> + def testInputSignatureForInputOptionsInvalidCombinations ( self , distribution , input_options ) : <nl> + def dataset_fn ( input_context ) : <nl> + return dataset_ops . Dataset . from_tensor_slices ( <nl> + np . full ( 4 , input_context . input_pipeline_id ) ) <nl> <nl> + with self . assertRaises ( ValueError ) : <nl> + ds = distribution . experimental_distribute_datasets_from_function ( <nl> + dataset_fn , input_options ) <nl> <nl> if __name__ = = " __main__ " : <nl> combinations . main ( ) <nl>
applying review changes p6 plus new tests
tensorflow/tensorflow
848e85aad0d8a328510a739dff1520f7cfd92893
2020-10-15T22:29:02Z
mmm a / tools / interop_matrix / client_matrix . py <nl> ppp b / tools / interop_matrix / client_matrix . py <nl> def __init__ ( self , patch = [ ] , runtimes = [ ] , testcases_file = None ) : <nl> ( ' v1 . 22 . 1 ' , ReleaseInfo ( ) ) , <nl> ( ' v1 . 23 . 0 ' , ReleaseInfo ( ) ) , <nl> ( ' v1 . 24 . 0 ' , ReleaseInfo ( ) ) , <nl> + ( ' v1 . 26 . 0 ' , ReleaseInfo ( ) ) , <nl> ] ) , <nl> ' go ' : <nl> OrderedDict ( <nl> def __init__ ( self , patch = [ ] , runtimes = [ ] , testcases_file = None ) : <nl> ( ' v1 . 22 . 1 ' , ReleaseInfo ( ) ) , <nl> ( ' v1 . 23 . 0 ' , ReleaseInfo ( ) ) , <nl> ( ' v1 . 24 . 0 ' , ReleaseInfo ( ) ) , <nl> + ( ' v1 . 26 . 0 ' , ReleaseInfo ( ) ) , <nl> ] ) , <nl> ' node ' : <nl> OrderedDict ( [ <nl> def __init__ ( self , patch = [ ] , runtimes = [ ] , testcases_file = None ) : <nl> # TODO : https : / / github . com / grpc / grpc / issues / 18262 . <nl> # If you are not encountering the error in above issue <nl> # go ahead and upload the docker image for new releases . <nl> + ( ' v1 . 26 . 0 ' , ReleaseInfo ( ) ) , <nl> ] ) , <nl> ' php ' : <nl> OrderedDict ( [ <nl> def __init__ ( self , patch = [ ] , runtimes = [ ] , testcases_file = None ) : <nl> ( ' v1 . 22 . 1 ' , ReleaseInfo ( ) ) , <nl> ( ' v1 . 23 . 0 ' , ReleaseInfo ( ) ) , <nl> ( ' v1 . 24 . 0 ' , ReleaseInfo ( ) ) , <nl> + ( ' v1 . 26 . 0 ' , ReleaseInfo ( ) ) , <nl> ] ) , <nl> ' csharp ' : <nl> OrderedDict ( [ <nl> def __init__ ( self , patch = [ ] , runtimes = [ ] , testcases_file = None ) : <nl> ( ' v1 . 22 . 1 ' , ReleaseInfo ( ) ) , <nl> ( ' v1 . 23 . 0 ' , ReleaseInfo ( ) ) , <nl> ( ' v1 . 24 . 0 ' , ReleaseInfo ( ) ) , <nl> + ( ' v1 . 26 . 0 ' , ReleaseInfo ( ) ) , <nl> ] ) , <nl> } <nl>
Merge pull request from gnossen / v1 . 26_interop
grpc/grpc
b1547c9d19034740b1e5b4d73cb91d068dc0acb4
2019-12-19T01:20:20Z
mmm a / tensorflow / go / op / wrappers . go <nl> ppp b / tensorflow / go / op / wrappers . go <nl> func TensorMapLookup ( scope * Scope , input_handle tf . Output , key tf . Output , value_ <nl> return op . Output ( 0 ) <nl> } <nl> <nl> - / / Merges summaries . <nl> - / / <nl> - / / This op creates a <nl> - / / [ ` Summary ` ] ( https : / / www . tensorflow . org / code / tensorflow / core / framework / summary . proto ) <nl> - / / protocol buffer that contains the union of all the values in the input <nl> - / / summaries . <nl> - / / <nl> - / / When the Op is run , it reports an ` InvalidArgument ` error if multiple values <nl> - / / in the summaries to merge use the same tag . <nl> - / / <nl> - / / Arguments : <nl> - / / inputs : Can be of any shape . Each must contain serialized ` Summary ` protocol <nl> - / / buffers . <nl> - / / <nl> - / / Returns Scalar . Serialized ` Summary ` protocol buffer . <nl> - func MergeSummary ( scope * Scope , inputs [ ] tf . Output ) ( summary tf . Output ) { <nl> - if scope . Err ( ) ! = nil { <nl> - return <nl> - } <nl> - opspec : = tf . OpSpec { <nl> - Type : " MergeSummary " , <nl> - Input : [ ] tf . Input { <nl> - tf . OutputList ( inputs ) , <nl> - } , <nl> - } <nl> - op : = scope . AddOperation ( opspec ) <nl> - return op . Output ( 0 ) <nl> - } <nl> - <nl> / / DecodeImageAttr is an optional argument to DecodeImage . <nl> type DecodeImageAttr func ( optionalAttr ) <nl> <nl> func SparseFillEmptyRowsGrad ( scope * Scope , reverse_index_map tf . Output , grad_val <nl> return op . Output ( 0 ) , op . Output ( 1 ) <nl> } <nl> <nl> + / / Merges summaries . <nl> + / / <nl> + / / This op creates a <nl> + / / [ ` Summary ` ] ( https : / / www . tensorflow . org / code / tensorflow / core / framework / summary . proto ) <nl> + / / protocol buffer that contains the union of all the values in the input <nl> + / / summaries . <nl> + / / <nl> + / / When the Op is run , it reports an ` InvalidArgument ` error if multiple values <nl> + / / in the summaries to merge use the same tag . <nl> + / / <nl> + / / Arguments : <nl> + / / inputs : Can be of any shape . Each must contain serialized ` Summary ` protocol <nl> + / / buffers . <nl> + / / <nl> + / / Returns Scalar . Serialized ` Summary ` protocol buffer . <nl> + func MergeSummary ( scope * Scope , inputs [ ] tf . Output ) ( summary tf . Output ) { <nl> + if scope . Err ( ) ! = nil { <nl> + return <nl> + } <nl> + opspec : = tf . OpSpec { <nl> + Type : " MergeSummary " , <nl> + Input : [ ] tf . Input { <nl> + tf . OutputList ( inputs ) , <nl> + } , <nl> + } <nl> + op : = scope . AddOperation ( opspec ) <nl> + return op . Output ( 0 ) <nl> + } <nl> + <nl> / / MaxPool3DGradAttr is an optional argument to MaxPool3DGrad . <nl> type MaxPool3DGradAttr func ( optionalAttr ) <nl> <nl>
Go : Update generated wrapper functions for TensorFlow ops .
tensorflow/tensorflow
5c06ed818381beaa015c8ea962aaecf0a5addab4
2020-08-24T19:00:03Z