text
stringlengths
2
1.04M
meta
dict
CTEST_BZR_COMMAND ----------------- Specify the CTest ``BZRCommand`` setting in a :manual:`ctest(1)` dashboard client script.
{ "content_hash": "4e88dde8fd4d5d89ab61ae6895d5dd58", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 48, "avg_line_length": 26.4, "alnum_prop": 0.6287878787878788, "repo_name": "pipou/rae", "id": "6c2dc32df4246f1b2c2b40f962ced90c819546e1", "size": "132", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "builder/cmake/windows/share/cmake-3.8/Help/variable/CTEST_BZR_COMMAND.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2544" }, { "name": "C", "bytes": "48544" }, { "name": "C++", "bytes": "6334" }, { "name": "CMake", "bytes": "8152333" }, { "name": "CSS", "bytes": "56991" }, { "name": "Cuda", "bytes": "901" }, { "name": "Emacs Lisp", "bytes": "44259" }, { "name": "Fortran", "bytes": "6400" }, { "name": "HTML", "bytes": "36295522" }, { "name": "JavaScript", "bytes": "296574" }, { "name": "M4", "bytes": "4433" }, { "name": "Roff", "bytes": "4627932" }, { "name": "Shell", "bytes": "59955" }, { "name": "Vim script", "bytes": "140497" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no"> <title>Quickstart | MSAL.JS with ADFS 2019 Vanilla JavaScript SPA</title> <!-- IE support: add promises polyfill before msal.js --> <script type="text/javascript" src="//cdn.jsdelivr.net/npm/bluebird@3.7.2/js/browser/bluebird.min.js"></script> <script src="./dist/msal.js"></script> <!-- adding Bootstrap 4 for UI components --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <a class="navbar-brand" href="/">MS Identity Platform</a> <div class="btn-group ml-auto dropleft"> <button type="button" id="SignIn" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Sign In </button> <div class="dropdown-menu"> <button class="dropdown-item" id="loginPopup" onclick="signIn(this.id)">Sign in using Popup</button> <button class="dropdown-item" id="loginRedirect" onclick="signIn(this.id)">Sign in using Redirect</button> </div> </div> </nav> <br> <h5 class="card-header text-center">Vanilla JavaScript SPA calling MS Graph API with MSAL.JS</h5> <br> <div class="row" style="margin:auto" > <div id="card-div" class="col-md-3" style="display:none"> <div class="card text-center"> <div class="card-body"> <h5 class="card-title" id="WelcomeMessage">Please sign-in to acquire an access token</h5> <div id="profile-div"></div> <br> <br> <button class="btn btn-primary" id="getAccessTokenRedirect" onclick="getAccessTokenRedirect()">Get Access Token (Redirect)</button> <br> <br> <button class="btn btn-primary" id="getAccessTokenPopup" onclick="getAccessTokenPopup()">Get Access Token (Popup)</button> <br> <br> <button class="btn btn-primary" id="getAccessTokenSilent" onclick="getAccessTokenSilent()">Get Access Token (Silent)</button> </div> </div> </div> <br> <br> <div class="col-md-4"> <div class="list-group" id="list-tab" role="tablist"> </div> </div> <div class="col-md-5"> <div class="tab-content" id="nav-tabContent"> </div> </div> </div> <br> <br> <!-- importing bootstrap.js and supporting js libraries --> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <!-- importing app scripts | load order is important --> <script type="text/javascript" src="./authConfig.js"></script> <script type="text/javascript" src="./ui.js"></script> <script type="text/javascript" src="./auth.js"></script> </body> </html>
{ "content_hash": "f920c0e88dc3744421e5f4cfac98be66", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 215, "avg_line_length": 49.273972602739725, "alnum_prop": 0.6561023074784542, "repo_name": "AzureAD/microsoft-authentication-library-for-js", "id": "abef0cd5fe23ce8be855e7e5793ea0813f409686", "size": "3597", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "samples/msal-core-samples/VanillaJSTestApp/app/adfs/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "3421" }, { "name": "C", "bytes": "199" }, { "name": "C++", "bytes": "3861" }, { "name": "CSS", "bytes": "345" }, { "name": "EJS", "bytes": "1365" }, { "name": "HTML", "bytes": "6370" }, { "name": "Java", "bytes": "14660" }, { "name": "JavaScript", "bytes": "2524257" }, { "name": "Python", "bytes": "979" }, { "name": "Shell", "bytes": "2665" }, { "name": "TypeScript", "bytes": "3471849" } ], "symlink_target": "" }
package monifu.reactive.channels import monifu.concurrent.Scheduler import monifu.reactive.OverflowStrategy.Evicted import monifu.reactive._ import monifu.reactive.observers.BufferedSubscriber /** * Wraps any [[Subject]] into a [[Channel]]. */ class SubjectChannel[I,+O] private[reactive] (subject: Subject[I, O], overflowStrategy: OverflowStrategy.Synchronous, onOverflow: Long => I, scheduler: Scheduler) extends ObservableChannel[I,O] { assert(onOverflow == null || overflowStrategy.isInstanceOf[Evicted], "onOverflow is only supported for `OverflowStrategy.WithSignal`") private[this] val channel = BufferedSubscriber( Subscriber(subject, scheduler), overflowStrategy, onOverflow) final def onSubscribe(subscriber: Subscriber[O]): Unit = { subject.onSubscribe(subscriber) } final def pushNext(elems: I*): Unit = { for (elem <- elems) channel.onNext(elem) } final def pushComplete(): Unit = { channel.onComplete() } final def pushError(ex: Throwable): Unit = { channel.onError(ex) } } object SubjectChannel { /** * Wraps any [[Subject]] into a [[Channel]]. * * @param strategy - the [[OverflowStrategy overflow strategy]] * used for buffering, which specifies what to do in case * we're dealing with slow consumers: should an unbounded * buffer be used, should back-pressure be applied, should * the pipeline drop newer or older events, should it drop * the whole buffer? See [[OverflowStrategy]] for more * details. */ def apply[I,O](subject: Subject[I, O], strategy: OverflowStrategy.Synchronous) (implicit s: Scheduler): SubjectChannel[I, O] = { new SubjectChannel[I,O](subject, strategy, null, s) } /** * Wraps any [[Subject]] into a [[Channel]]. * * @param strategy - the [[OverflowStrategy overflow strategy]] * used for buffering, which specifies what to do in case * we're dealing with slow consumers: should an unbounded * buffer be used, should back-pressure be applied, should * the pipeline drop newer or older events, should it drop * the whole buffer? See [[OverflowStrategy]] for more * details. * * @param onOverflow - a function that is used for signaling a special * event used to inform the consumers that an overflow event * happened, function that receives the number of dropped * events as a parameter (see [[OverflowStrategy.Evicted]]) */ def apply[I,O](subject: Subject[I, O], strategy: OverflowStrategy.Evicted, onOverflow: Long => I) (implicit s: Scheduler): SubjectChannel[I, O] = { new SubjectChannel[I,O](subject, strategy, onOverflow, s) } }
{ "content_hash": "0cb01d557551d6db8d5a2d7fd857b5b1", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 121, "avg_line_length": 34.835443037974684, "alnum_prop": 0.6780523255813954, "repo_name": "sergius/monifu", "id": "5a551af43deb5a063752231ae3ac2ba7364a6049", "size": "3435", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "monifu/shared/src/main/scala/monifu/reactive/channels/SubjectChannel.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "1278891" } ], "symlink_target": "" }
#import "TiBase.h" #ifdef USE_TI_MAP #import <MapKit/MapKit.h> #import "TiMapView.h" @interface TiMapImageAnnotationView : MKAnnotationView<TiMapAnnotation> { @private TiMapView *map; BOOL observing; NSString * lastHitName; } - (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier map:(TiMapView*)map image:(UIImage*)image; -(NSString *)lastHitName; @end #endif
{ "content_hash": "027ea5a3f9d4c9058ab9f7094a87e72a", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 141, "avg_line_length": 19.80952380952381, "alnum_prop": 0.7620192307692307, "repo_name": "jraines/game-of-life-ipad", "id": "f2f84004ef270ff4a430ef70c976630e5aecea72", "size": "725", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/iphone/Classes/TiMapImageAnnotationView.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "218258" }, { "name": "C++", "bytes": "57221" }, { "name": "CoffeeScript", "bytes": "1834" }, { "name": "JavaScript", "bytes": "2998" }, { "name": "Objective-C", "bytes": "2798037" }, { "name": "Shell", "bytes": "132" } ], "symlink_target": "" }
package edu.mayo.cts2.framework.webapp.soap.endpoint.codesystem; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.springframework.ws.server.endpoint.annotation.Endpoint; import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.springframework.ws.server.endpoint.annotation.RequestPayload; import org.springframework.ws.server.endpoint.annotation.ResponsePayload; import edu.mayo.cts2.framework.model.codesystem.CodeSystemCatalogEntryDirectory; import edu.mayo.cts2.framework.model.codesystem.CodeSystemCatalogEntrySummary; import edu.mayo.cts2.framework.model.command.Page; import edu.mayo.cts2.framework.model.command.ResolvedFilter; import edu.mayo.cts2.framework.model.command.ResolvedReadContext; import edu.mayo.cts2.framework.model.directory.DirectoryResult; import edu.mayo.cts2.framework.model.service.core.FilterComponent; import edu.mayo.cts2.framework.model.service.core.Query; import edu.mayo.cts2.framework.model.service.core.QueryControl; import edu.mayo.cts2.framework.model.wsdl.basequeryservice.GetKnownProperty; import edu.mayo.cts2.framework.model.wsdl.basequeryservice.GetKnownPropertyResponse; import edu.mayo.cts2.framework.model.wsdl.basequeryservice.GetSupportedMatchAlgorithm; import edu.mayo.cts2.framework.model.wsdl.basequeryservice.GetSupportedMatchAlgorithmResponse; import edu.mayo.cts2.framework.model.wsdl.basequeryservice.GetSupportedModelAttribute; import edu.mayo.cts2.framework.model.wsdl.basequeryservice.GetSupportedModelAttributeResponse; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.Count; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.CountResponse; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.Difference; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.DifferenceResponse; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.GetAllCodeSystems; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.GetAllCodeSystemsResponse; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.Intersect; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.IntersectResponse; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.Resolve; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.ResolveResponse; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.Restrict; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.RestrictResponse; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.Union; import edu.mayo.cts2.framework.model.wsdl.codesystemquery.UnionResponse; import edu.mayo.cts2.framework.service.profile.ResourceQuery; import edu.mayo.cts2.framework.service.profile.codesystem.CodeSystemQueryService; import edu.mayo.cts2.framework.webapp.soap.directoryuri.DirectoryUriUtils; import edu.mayo.cts2.framework.webapp.soap.directoryuri.SoapDirectoryUri; import edu.mayo.cts2.framework.webapp.soap.directoryuri.SoapDirectoryUriRequest; import edu.mayo.cts2.framework.webapp.soap.endpoint.AbstractQueryServiceEndpoint; import edu.mayo.cts2.framework.webapp.soap.resolver.FilterResolver; @Endpoint("CodeSystemCatalogQueryServicesEndpoint") public class CodeSystemCatalogQueryServicesEndpoint extends AbstractQueryServiceEndpoint { @Cts2Service private CodeSystemQueryService codeSystemQueryService; @PayloadRoot(localPart = "getAllCodeSystems", namespace = CTS2_NAMESPACE_ROOT + "CodeSystemCatalogQueryServices") @ResponsePayload public GetAllCodeSystemsResponse getAllCodeSystems(@RequestPayload final GetAllCodeSystems request) { GetAllCodeSystemsResponse response = new GetAllCodeSystemsResponse(); SoapDirectoryUriRequest<?> directoryUri = (SoapDirectoryUriRequest<?>) DirectoryUriUtils.buildSoapDirectoryUriRequest(0, null, null); response.setReturn(DirectoryUriUtils.serialize(directoryUri)); return response; } @PayloadRoot(localPart = "resolve", namespace = CTS2_NAMESPACE_ROOT + "CodeSystemCatalogQueryServices") @ResponsePayload public ResolveResponse resolve(@RequestPayload final Resolve request) { return this.doResolve(this.codeSystemQueryService, request, CodeSystemCatalogEntryDirectory.class, new ResponseBuilder<ResolveResponse, CodeSystemCatalogEntryDirectory>() { @Override public ResolveResponse buildResponse(CodeSystemCatalogEntryDirectory directory) { ResolveResponse response = new ResolveResponse(); response.setCodeSystemCatalogEntryDirectory(directory); return response; } }); } @PayloadRoot(localPart = "getSupportMatchAlgorithm", namespace = CTS2_NAMESPACE_ROOT + "CodeSystemCatalogQueryServices") @ResponsePayload public GetSupportedMatchAlgorithmResponse getSupportMatchAlgorithm(@RequestPayload GetSupportedMatchAlgorithm request) { GetSupportedMatchAlgorithmResponse response = new GetSupportedMatchAlgorithmResponse(); // response.setReturn(this.codeSystemQueryService.getSupportedMatchAlgorithms()); return response; } @PayloadRoot(localPart = "getSupportedModelAttribute", namespace = CTS2_NAMESPACE_ROOT + "CodeSystemCatalogQueryServices") @ResponsePayload public GetSupportedModelAttributeResponse getSupportedModelAttribute(@RequestPayload GetSupportedModelAttribute request) { GetSupportedModelAttributeResponse response = new GetSupportedModelAttributeResponse(); return response; } @PayloadRoot(localPart = "getKnownProperty", namespace = CTS2_NAMESPACE_ROOT + "CodeSystemCatalogQueryServices") @ResponsePayload public GetKnownPropertyResponse getKnownProperty(@RequestPayload GetKnownProperty request) { GetKnownPropertyResponse response = new GetKnownPropertyResponse(); return response; } @PayloadRoot(localPart = "count", namespace = CTS2_NAMESPACE_ROOT + "CodeSystemCatalogQueryServices") @ResponsePayload public CountResponse count(@RequestPayload Count request) { CountResponse response = new CountResponse(); return response; } @PayloadRoot(localPart = "difference", namespace = CTS2_NAMESPACE_ROOT + "CodeSystemCatalogQueryServices") @ResponsePayload public DifferenceResponse difference(@RequestPayload Difference request) { DifferenceResponse response = new DifferenceResponse(); return response; } @PayloadRoot(localPart = "intersect", namespace = CTS2_NAMESPACE_ROOT + "CodeSystemCatalogQueryServices") @ResponsePayload public IntersectResponse intersect(@RequestPayload Intersect request) { IntersectResponse response = new IntersectResponse(); return response; } @PayloadRoot(localPart = "restrict", namespace = CTS2_NAMESPACE_ROOT + "CodeSystemCatalogQueryServices") @ResponsePayload public RestrictResponse restrict(@RequestPayload Restrict request) { RestrictResponse response = new RestrictResponse(); return response; } @PayloadRoot(localPart = "union", namespace = CTS2_NAMESPACE_ROOT + "CodeSystemCatalogQueryServices") @ResponsePayload public UnionResponse union(@RequestPayload Union request) { UnionResponse response = new UnionResponse(); return response; } }
{ "content_hash": "695d228554570c1db078451966139a55", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 124, "avg_line_length": 49.875, "alnum_prop": 0.8189919242550822, "repo_name": "cts2/cts2-framework", "id": "9e1d7148ec1bb687d40e9016bb6e9b4da91f2901", "size": "7182", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cts2-webapp/src/main/java/edu/mayo/cts2/framework/webapp/soap/endpoint/codesystem/CodeSystemCatalogQueryServicesEndpoint.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "45494" }, { "name": "Groovy", "bytes": "89933" }, { "name": "HTML", "bytes": "19520" }, { "name": "Java", "bytes": "1387010" }, { "name": "JavaScript", "bytes": "409200" }, { "name": "XSLT", "bytes": "22084" } ], "symlink_target": "" }
Ce package permet de gérer votre équipe avec l'application slack : > https://slack.com Les élèves doivent posséder un compte dans votre domaine slack. Les comptes sont ensuite utilisés par l'application pour gérer les droits et accéder aux fonctionnalités de l'application. ## Configuration Créer un dans votre slack : > https://my.slack.com/services/new/bot and copy the token Récupérer le token et copier le dans le fichier suivant : > server/slack-token-sample.js Il ne vous reste plus qu'à copier ou renommer le fichier : > server/slack-token.js TODO: * Reprendre la présentation de slack
{ "content_hash": "31b872d273e65b7d961e4276d063b7ef", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 122, "avg_line_length": 35.11764705882353, "alnum_prop": 0.7839195979899497, "repo_name": "goacademie/fanhui", "id": "6183c5fd845e49f38d06850c305fdf4f99b5bb30", "size": "633", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/slack-inseis/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "369" }, { "name": "HTML", "bytes": "10525" }, { "name": "JavaScript", "bytes": "23856" } ], "symlink_target": "" }
class AddVolumeNumberToManifestation < ActiveRecord::Migration[4.2] def self.up add_column :manifestations, :volume_number, :integer add_column :manifestations, :issue_number, :integer add_column :manifestations, :serial_number, :integer end def self.down remove_column :manifestations, :serial_number remove_column :manifestations, :issue_number remove_column :manifestations, :volume_number end end
{ "content_hash": "448093182523ff66ee9f4682f6b75396", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 67, "avg_line_length": 33.38461538461539, "alnum_prop": 0.7488479262672811, "repo_name": "next-l/enju_leaf", "id": "f9f79e939eae844e354ad22d5140cb5df1b85c94", "size": "434", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "db/migrate/20110916091020_add_volume_number_to_manifestation.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "42158" }, { "name": "Dockerfile", "bytes": "735" }, { "name": "HTML", "bytes": "743781" }, { "name": "JavaScript", "bytes": "386024" }, { "name": "Ruby", "bytes": "2482791" }, { "name": "Slim", "bytes": "1892" } ], "symlink_target": "" }
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'rack/session/smart_cookie' require 'minitest/autorun'
{ "content_hash": "6068b1c979f2dedb230377b2dcd66fe6", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 58, "avg_line_length": 30.75, "alnum_prop": 0.7073170731707317, "repo_name": "mwpastore/rack-session-smart_cookie", "id": "ccbf06d43a0c7e7bfe2bd7afd2bdcbc7f985918b", "size": "123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "12825" }, { "name": "Shell", "bytes": "74" } ], "symlink_target": "" }
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @file RequesterAttributes.hpp */ #ifndef REQUESTERATTRIBUTES_HPP_ #define REQUESTERATTRIBUTES_HPP_ #include "PublisherAttributes.h" #include "SubscriberAttributes.h" namespace eprosima { namespace fastrtps { class RequesterAttributes { public: RequesterAttributes() = default; bool operator==(const RequesterAttributes& b) const { return (this->service_name == b.service_name) && (this->request_topic_name == b.request_topic_name) && (this->reply_topic_name == b.reply_topic_name) && (this->publisher == b.publisher) && (this->subscriber == b.subscriber); } std::string service_name; std::string request_type; std::string reply_type; std::string request_topic_name; std::string reply_topic_name; PublisherAttributes publisher; SubscriberAttributes subscriber; }; } /* namespace fastrtps */ } /* namespace eprosima */ #endif /* REQUESTERATTRIBUTES_HPP_ */
{ "content_hash": "123e76b298e32d5a40c82fac3ff6d992", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 75, "avg_line_length": 29.327272727272728, "alnum_prop": 0.6924984500929944, "repo_name": "eProsima/Fast-DDS", "id": "ed0423405387a1f1b39f2ce44fd054466a522b33", "size": "1613", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/fastrtps/attributes/RequesterAttributes.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "874" }, { "name": "C", "bytes": "9035166" }, { "name": "C++", "bytes": "19044069" }, { "name": "CMake", "bytes": "450920" }, { "name": "CSS", "bytes": "28054" }, { "name": "HTML", "bytes": "2698" }, { "name": "M4", "bytes": "12825" }, { "name": "PowerShell", "bytes": "954" }, { "name": "Python", "bytes": "125888" }, { "name": "Shell", "bytes": "5639" } ], "symlink_target": "" }
<a href="https://travis-ci.org/Xotic750/normalize-space-x" title="Travis status"> <img src="https://travis-ci.org/Xotic750/normalize-space-x.svg?branch=master" alt="Travis status" height="18"/> </a> <a href="https://david-dm.org/Xotic750/normalize-space-x" title="Dependency status"> <img src="https://david-dm.org/Xotic750/normalize-space-x.svg" alt="Dependency status" height="18"/> </a> <a href="https://david-dm.org/Xotic750/normalize-space-x#info=devDependencies" title="devDependency status"> <img src="https://david-dm.org/Xotic750/normalize-space-x/dev-status.svg" alt="devDependency status" height="18"/> </a> <a href="https://badge.fury.io/js/normalize-space-x" title="npm version"> <img src="https://badge.fury.io/js/normalize-space-x.svg" alt="npm version" height="18"/> </a> <a name="module_normalize-space-x"></a> ## normalize-space-x Trims and replaces sequences of whitespace characters by a single space. **Version**: 2.0.0 **Author**: Xotic750 <Xotic750@gmail.com> **License**: [MIT](&lt;https://opensource.org/licenses/MIT&gt;) **Copyright**: Xotic750 <a name="exp_module_normalize-space-x--module.exports"></a> ### `module.exports(string)` ⇒ <code>string</code> ⏏ This method strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string. **Kind**: Exported function **Returns**: <code>string</code> - The normalized string. **Throws**: - <code>TypeError</code> If string is null or undefined or not coercible. | Param | Type | Description | | --- | --- | --- | | string | <code>string</code> | The string to be normalized. | **Example** ```js var normalizeSpace = require('normalize-space-x'); normalizeSpace(' \t\na \t\nb \t\n') === 'a b'; // true ```
{ "content_hash": "0991e730d48872a74895f51bb7deb2bf", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 78, "avg_line_length": 34.15094339622642, "alnum_prop": 0.6906077348066298, "repo_name": "bourdakos1/Visual-Recognition-Tool", "id": "363b3bd49906046d4a30edb43ec48d012df486e2", "size": "1814", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/normalize-space-x/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "157500" }, { "name": "Ruby", "bytes": "567" }, { "name": "Swift", "bytes": "189427" } ], "symlink_target": "" }
class AudioStreamPlayer2D : public Node2D { GDCLASS(AudioStreamPlayer2D, Node2D) private: enum { MAX_OUTPUTS = 8, MAX_INTERSECT_AREAS = 32 }; struct Output { AudioFrame vol; int bus_index; Viewport *viewport; //pointer only used for reference to previous mix }; Output outputs[MAX_OUTPUTS]; volatile int output_count; volatile bool output_ready; //these are used by audio thread to have a reference of previous volumes (for ramping volume and avoiding clicks) Output prev_outputs[MAX_OUTPUTS]; int prev_output_count; Ref<AudioStreamPlayback> stream_playback; Ref<AudioStream> stream; Vector<AudioFrame> mix_buffer; volatile float setseek; volatile bool active; volatile float setplay; float volume_db; bool autoplay; StringName bus; void _mix_audio(); static void _mix_audios(void *self) { reinterpret_cast<AudioStreamPlayer2D *>(self)->_mix_audio(); } void _set_playing(bool p_enable); bool _is_active() const; void _bus_layout_changed(); uint32_t area_mask; float max_distance; float attenuation; protected: void _validate_property(PropertyInfo &property) const; void _notification(int p_what); static void _bind_methods(); public: void set_stream(Ref<AudioStream> p_stream); Ref<AudioStream> get_stream() const; void set_volume_db(float p_volume); float get_volume_db() const; void play(float p_from_pos = 0.0); void seek(float p_seconds); void stop(); bool is_playing() const; float get_pos(); void set_bus(const StringName &p_bus); StringName get_bus() const; void set_autoplay(bool p_enable); bool is_autoplay_enabled(); void set_max_distance(float p_pixels); float get_max_distance() const; void set_attenuation(float p_curve); float get_attenuation() const; void set_area_mask(uint32_t p_mask); uint32_t get_area_mask() const; AudioStreamPlayer2D(); ~AudioStreamPlayer2D(); }; #endif
{ "content_hash": "6d708b9474e5c7d2b1648cac81c52ddb", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 114, "avg_line_length": 21.123595505617978, "alnum_prop": 0.7281914893617021, "repo_name": "exabon/godot", "id": "25eff61b761a5ff960f4669ea131d39f58ad796f", "size": "2052", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "scene/2d/audio_stream_player_2d.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "50004" }, { "name": "C++", "bytes": "17000821" }, { "name": "HTML", "bytes": "10302" }, { "name": "Java", "bytes": "497034" }, { "name": "Makefile", "bytes": "451" }, { "name": "Objective-C", "bytes": "2644" }, { "name": "Objective-C++", "bytes": "146830" }, { "name": "Python", "bytes": "268690" }, { "name": "Shell", "bytes": "11105" } ], "symlink_target": "" }
Link::Link(Universe* universe, Object* source, Object* destination) : m_universe(universe), m_source(source), m_destination(destination) { } Link::~Link() { } void Link::tick(float adjustment) { // Calculate the geometry of the shape. // Get the positions of the objects. sf::Vector2f sourcePos{m_source->getPos()}; sf::Vector2f destinationPos{m_destination->getPos()}; // Get the direction and distance. float directionToDestination = directionBetween(sourcePos, destinationPos); float distanceToDestination = distanceBetween(sourcePos, destinationPos); m_shape.setSize(sf::Vector2f{distanceToDestination, 5.f}); m_shape.setOrigin(sf::Vector2f{0.f, -10.f}); m_shape.setRotation(directionToDestination); } void Link::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform.translate(m_source->getPos()); target.draw(m_shape, states); }
{ "content_hash": "d5a958f880c844ef7ab5b98a68e0dd79", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 77, "avg_line_length": 34.30769230769231, "alnum_prop": 0.7387892376681614, "repo_name": "tiaanl/SpaceGame", "id": "970f1520bbb0fb78bb874d0a32b41f3ff1a33f90", "size": "1792", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/universe/link.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "148874" }, { "name": "CMake", "bytes": "1853" }, { "name": "Python", "bytes": "5395" } ], "symlink_target": "" }
mkdir build cd build || exit 1 cmake \ "${KDE_OPT_ARGS}" \ -DKDE_PLATFORM_FEATURE_DISABLE_DEPRECATED=TRUE \ -DCMAKE_C_FLAGS:STRING="${SLKCFLAGS}" \ -DCMAKE_C_FLAGS_RELEASE:STRING="${SLKCFLAGS}" \ -DCMAKE_CXX_FLAGS:STRING="${SLKCFLAGS}" \ -DCMAKE_CXX_FLAGS_RELEASE:STRING="${SLKCFLAGS}" \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ -DMAN_INSTALL_DIR=/usr/man \ -DSYSCONF_INSTALL_DIR=/etc/kde \ -DLIB_SUFFIX="${LIBDIRSUFFIX}" \ -DLIB_INSTALL_DIR="/usr/lib${LIBDIRSUFFIX}" \ -DLIBEXEC_INSTALL_DIR="/usr/lib${LIBDIRSUFFIX}" \ -DQT_PLUGIN_INSTALL_DIR="/usr/lib${LIBDIRSUFFIX}/qt5/plugins" \ -DQML_INSTALL_DIR="/usr/lib${LIBDIRSUFFIX}/qt5/qml" \ -DKDE_INSTALL_USE_QT_SYS_PATHS=ON \ -DBUILD_TESTING=OFF \ -DQca-qt5_DIR="/usr/lib${LIBDIRSUFFIX}/cmake/Qca" \ -DBalooWidgets_DIR="/usr/lib${LIBDIRSUFFIX}/cmake/KF5BalooWidgets" \ -DBaloo_DIR="/usr/lib${LIBDIRSUFFIX}/cmake/KF5Baloo" \ ..
{ "content_hash": "99ca4029d1e6311c2cea12224211dd0d", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 72, "avg_line_length": 40.708333333333336, "alnum_prop": 0.6530194472876152, "repo_name": "MyRequiem/KDE-Plasma5-build-system", "id": "5cb53102362ec155a30487ceb957553534c604a4", "size": "990", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmake/kde-baseapps.sh", "mode": "33188", "license": "mit", "language": [ { "name": "Elixir", "bytes": "107" }, { "name": "Shell", "bytes": "308856" } ], "symlink_target": "" }
package qemu import ( "fmt" "path/filepath" "github.com/hashicorp/packer/packer" "github.com/mitchellh/multistep" ) // This step creates the virtual disk that will be used as the // hard drive for the virtual machine. type stepCreateDisk struct{} func (s *stepCreateDisk) Run(state multistep.StateBag) multistep.StepAction { config := state.Get("config").(*Config) driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) name := config.VMName path := filepath.Join(config.OutputDir, name) command := []string{ "create", "-f", config.Format, path, fmt.Sprintf("%vM", config.DiskSize), } if config.DiskImage == true { return multistep.ActionContinue } ui.Say("Creating hard drive...") if err := driver.QemuImg(command...); err != nil { err := fmt.Errorf("Error creating hard drive: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } state.Put("disk_filename", name) return multistep.ActionContinue } func (s *stepCreateDisk) Cleanup(state multistep.StateBag) {}
{ "content_hash": "37a7a64bf45bccf9f8c8629e9527bdb1", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 77, "avg_line_length": 23, "alnum_prop": 0.6956521739130435, "repo_name": "deasmi/terraform-provider-libvirt", "id": "5d844e2a0f301c8493acf9734cc0722dc70f3380", "size": "1058", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "vendor/github.com/mitchellh/packer/builder/qemu/step_create_disk.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "178528" }, { "name": "HTML", "bytes": "1555" }, { "name": "Makefile", "bytes": "508" }, { "name": "Shell", "bytes": "2852" } ], "symlink_target": "" }
/** * @ngdoc object * @name ui.router.state.$stateProvider * * @requires ui.router.router.$urlRouterProvider * @requires ui.router.util.$urlMatcherFactoryProvider * @requires $locationProvider * * @description * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely * on state. * * A state corresponds to a "place" in the application in terms of the overall UI and * navigation. A state describes (via the controller / template / view properties) what * the UI looks like and does at that place. * * States often have things in common, and the primary way of factoring out these * commonalities in this model is via the state hierarchy, i.e. parent/child states aka * nested states. * * The `$stateProvider` provides interfaces to declare these states for your app. */ $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider', '$locationProvider']; function $StateProvider( $urlRouterProvider, $urlMatcherFactory, $locationProvider) { var root, states = {}, $state, queue = {}, abstractKey = 'abstract'; // Builds state properties from definition passed to registerState() var stateBuilder = { // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined. // state.children = []; // if (parent) parent.children.push(state); parent: function(state) { if (isDefined(state.parent) && state.parent) return findState(state.parent); // regex matches any valid composite state name // would match "contact.list" but not "contacts" var compositeName = /^(.+)\.[^.]+$/.exec(state.name); return compositeName ? findState(compositeName[1]) : root; }, // inherit 'data' from parent and override by own values (if any) data: function(state) { if (state.parent && state.parent.data) { state.data = state.self.data = extend({}, state.parent.data, state.data); } return state.data; }, // Build a URLMatcher if necessary, either via a relative or absolute URL url: function(state) { var url = state.url; if (isString(url)) { if (url.charAt(0) == '^') { return $urlMatcherFactory.compile(url.substring(1)); } return (state.parent.navigable || root).url.concat(url); } if ($urlMatcherFactory.isMatcher(url) || url == null) { return url; } throw new Error("Invalid url '" + url + "' in state '" + state + "'"); }, // Keep track of the closest ancestor state that has a URL (i.e. is navigable) navigable: function(state) { return state.url ? state : (state.parent ? state.parent.navigable : null); }, // Derive parameters for this state and ensure they're a super-set of parent's parameters params: function(state) { if (!state.params) { return state.url ? state.url.parameters() : state.parent.params; } if (!isArray(state.params)) throw new Error("Invalid params in state '" + state + "'"); if (state.url) throw new Error("Both params and url specicified in state '" + state + "'"); return state.params; }, // If there is no explicit multi-view configuration, make one up so we don't have // to handle both cases in the view directive later. Note that having an explicit // 'views' property will mean the default unnamed view properties are ignored. This // is also a good time to resolve view names to absolute names, so everything is a // straight lookup at link time. views: function(state) { var views = {}; forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) { if (name.indexOf('@') < 0) name += '@' + state.parent.name; views[name] = view; }); return views; }, ownParams: function(state) { if (!state.parent) { return state.params; } var paramNames = {}; forEach(state.params, function (p) { paramNames[p] = true; }); forEach(state.parent.params, function (p) { if (!paramNames[p]) { throw new Error("Missing required parameter '" + p + "' in state '" + state.name + "'"); } paramNames[p] = false; }); var ownParams = []; forEach(paramNames, function (own, p) { if (own) ownParams.push(p); }); return ownParams; }, // Keep a full path from the root down to this state as this is needed for state activation. path: function(state) { return state.parent ? state.parent.path.concat(state) : []; // exclude root from path }, // Speed up $state.contains() as it's used a lot includes: function(state) { var includes = state.parent ? extend({}, state.parent.includes) : {}; includes[state.name] = true; return includes; }, $delegates: {} }; function isRelative(stateName) { return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0; } function findState(stateOrName, base) { var isStr = isString(stateOrName), name = isStr ? stateOrName : stateOrName.name, path = isRelative(name); if (path) { if (!base) throw new Error("No reference point given for path '" + name + "'"); var rel = name.split("."), i = 0, pathLength = rel.length, current = base; for (; i < pathLength; i++) { if (rel[i] === "" && i === 0) { current = base; continue; } if (rel[i] === "^") { if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'"); current = current.parent; continue; } break; } rel = rel.slice(i).join("."); name = current.name + (current.name && rel ? "." : "") + rel; } var state = states[name]; if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) { return state; } return undefined; } function queueState(parentName, state) { if (!queue[parentName]) { queue[parentName] = []; } queue[parentName].push(state); } function registerState(state) { // Wrap a new object around the state so we can store our private details easily. state = inherit(state, { self: state, resolve: state.resolve || {}, toString: function() { return this.name; } }); var name = state.name; if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name"); if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined"); // Get parent name var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.')) : (isString(state.parent)) ? state.parent : ''; // If parent is not registered yet, add state to queue and register later if (parentName && !states[parentName]) { return queueState(parentName, state.self); } for (var key in stateBuilder) { if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]); } states[name] = state; // Register the state in the global state list and with $urlRouter if necessary. if (!state[abstractKey] && state.url) { $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) { if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) { $state.transitionTo(state, $match, { location: false }); } }]); } // Register any queued children if (queue[name]) { for (var i = 0; i < queue[name].length; i++) { registerState(queue[name][i]); } } return state; } // Checks text to see if it looks like a glob. function isGlob (text) { return text.indexOf('*') > -1; } // Returns true if glob matches current $state name. function doesStateMatchGlob (glob) { var globSegments = glob.split('.'), segments = $state.$current.name.split('.'); //match greedy starts if (globSegments[0] === '**') { segments = segments.slice(segments.indexOf(globSegments[1])); segments.unshift('**'); } //match greedy ends if (globSegments[globSegments.length - 1] === '**') { segments.splice(segments.indexOf(globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE); segments.push('**'); } if (globSegments.length != segments.length) { return false; } //match single stars for (var i = 0, l = globSegments.length; i < l; i++) { if (globSegments[i] === '*') { segments[i] = '*'; } } return segments.join('') === globSegments.join(''); } // Implicit root state that is always active root = registerState({ name: '', url: '^', views: null, 'abstract': true }); root.navigable = null; /** * @ngdoc function * @name ui.router.state.$stateProvider#decorator * @methodOf ui.router.state.$stateProvider * * @description * Allows you to extend (carefully) or override (at your own peril) the * `stateBuilder` object used internally by `$stateProvider`. This can be used * to add custom functionality to ui-router, for example inferring templateUrl * based on the state name. * * When passing only a name, it returns the current (original or decorated) builder * function that matches `name`. * * The builder functions that can be decorated are listed below. Though not all * necessarily have a good use case for decoration, that is up to you to decide. * * In addition, users can attach custom decorators, which will generate new * properties within the state's internal definition. There is currently no clear * use-case for this beyond accessing internal states (i.e. $state.$current), * however, expect this to become increasingly relevant as we introduce additional * meta-programming features. * * **Warning**: Decorators should not be interdependent because the order of * execution of the builder functions in non-deterministic. Builder functions * should only be dependent on the state definition object and super function. * * * Existing builder functions and current return values: * * - **parent** `{object}` - returns the parent state object. * - **data** `{object}` - returns state data, including any inherited data that is not * overridden by own values (if any). * - **url** `{object}` - returns a {link ui.router.util.type:UrlMatcher} or null. * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is * navigable). * - **params** `{object}` - returns an array of state params that are ensured to * be a super-set of parent's params. * - **views** `{object}` - returns a views object where each key is an absolute view * name (i.e. "viewName@stateName") and each value is the config object * (template, controller) for the view. Even when you don't use the views object * explicitly on a state config, one is still created for you internally. * So by decorating this builder function you have access to decorating template * and controller properties. * - **ownParams** `{object}` - returns an array of params that belong to the state, * not including any params defined by ancestor states. * - **path** `{string}` - returns the full path from the root down to this state. * Needed for state activation. * - **includes** `{object}` - returns an object that includes every state that * would pass a '$state.includes()' test. * * @example * <pre> * // Override the internal 'views' builder with a function that takes the state * // definition, and a reference to the internal function being overridden: * $stateProvider.decorator('views', function ($state, parent) { * var result = {}, * views = parent(state); * * angular.forEach(view, function (config, name) { * var autoName = (state.name + '.' + name).replace('.', '/'); * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html'; * result[name] = config; * }); * return result; * }); * * $stateProvider.state('home', { * views: { * 'contact.list': { controller: 'ListController' }, * 'contact.item': { controller: 'ItemController' } * } * }); * * // ... * * $state.go('home'); * // Auto-populates list and item views with /partials/home/contact/list.html, * // and /partials/home/contact/item.html, respectively. * </pre> * * @param {string} name The name of the builder function to decorate. * @param {object} func A function that is responsible for decorating the original * builder function. The function receives two parameters: * * - `{object}` - state - The state config object. * - `{object}` - super - The original builder function. * * @return {object} $stateProvider - $stateProvider instance */ this.decorator = decorator; function decorator(name, func) { /*jshint validthis: true */ if (isString(name) && !isDefined(func)) { return stateBuilder[name]; } if (!isFunction(func) || !isString(name)) { return this; } if (stateBuilder[name] && !stateBuilder.$delegates[name]) { stateBuilder.$delegates[name] = stateBuilder[name]; } stateBuilder[name] = func; return this; } /** * @ngdoc function * @name ui.router.state.$stateProvider#state * @methodOf ui.router.state.$stateProvider * * @description * Registers a state configuration under a given state name. The stateConfig object * has the following acceptable properties. * * <a id='template'></a> * * - **`template`** - {string|function=} - html template as a string or a function that returns * an html template as a string which should be used by the uiView directives. This property * takes precedence over templateUrl. * * If `template` is a function, it will be called with the following parameters: * * - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by * applying the current state * * <a id='templateUrl'></a> * * - **`templateUrl`** - {string|function=} - path or function that returns a path to an html * template that should be used by uiView. * * If `templateUrl` is a function, it will be called with the following parameters: * * - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by * applying the current state * * <a id='templateProvider'></a> * * - **`templateProvider`** - {function=} - Provider function that returns HTML content * string. * * <a id='controller'></a> * * - **`controller`** - {string|function=} - Controller fn that should be associated with newly * related scope or the name of a registered controller if passed as a string. * * <a id='controllerProvider'></a> * * - **`controllerProvider`** - {function=} - Injectable provider function that returns * the actual controller or string. * * <a id='controllerAs'></a> * * - **`controllerAs`** – {string=} – A controller alias name. If present the controller will be * published to scope under the controllerAs name. * * <a id='resolve'></a> * * - **`resolve`** - {object.&lt;string, function&gt;=} - An optional map of dependencies which * should be injected into the controller. If any of these dependencies are promises, * the router will wait for them all to be resolved or one to be rejected before the * controller is instantiated. If all the promises are resolved successfully, the values * of the resolved promises are injected and $stateChangeSuccess event is fired. If any * of the promises are rejected the $stateChangeError event is fired. The map object is: * * - key - {string}: name of dependency to be injected into controller * - factory - {string|function}: If string then it is alias for service. Otherwise if function, * it is injected and return value it treated as dependency. If result is a promise, it is * resolved before its value is injected into controller. * * <a id='url'></a> * * - **`url`** - {string=} - A url with optional parameters. When a state is navigated or * transitioned to, the `$stateParams` service will be populated with any * parameters that were passed. * * <a id='params'></a> * * - **`params`** - {object=} - An array of parameter names or regular expressions. Only * use this within a state if you are not using url. Otherwise you can specify your * parameters within the url. When a state is navigated or transitioned to, the * $stateParams service will be populated with any parameters that were passed. * * <a id='views'></a> * * - **`views`** - {object=} - Use the views property to set up multiple views or to target views * manually/explicitly. * * <a id='abstract'></a> * * - **`abstract`** - {boolean=} - An abstract state will never be directly activated, * but can provide inherited properties to its common children states. * * <a id='onEnter'></a> * * - **`onEnter`** - {object=} - Callback function for when a state is entered. Good way * to trigger an action or dispatch an event, such as opening a dialog. * * <a id='onExit'></a> * * - **`onExit`** - {object=} - Callback function for when a state is exited. Good way to * trigger an action or dispatch an event, such as opening a dialog. * * <a id='reloadOnSearch'></a> * * - **`reloadOnSearch = true`** - {boolean=} - If `false`, will not retrigger the same state * just because a search/query parameter has changed (via $location.search() or $location.hash()). * Useful for when you'd like to modify $location.search() without triggering a reload. * * <a id='data'></a> * * - **`data`** - {object=} - Arbitrary data object, useful for custom configuration. * * @example * <pre> * // Some state name examples * * // stateName can be a single top-level name (must be unique). * $stateProvider.state("home", {}); * * // Or it can be a nested state name. This state is a child of the * // above "home" state. * $stateProvider.state("home.newest", {}); * * // Nest states as deeply as needed. * $stateProvider.state("home.newest.abc.xyz.inception", {}); * * // state() returns $stateProvider, so you can chain state declarations. * $stateProvider * .state("home", {}) * .state("about", {}) * .state("contacts", {}); * </pre> * * @param {string} name A unique state name, e.g. "home", "about", "contacts". * To create a parent/child state use a dot, e.g. "about.sales", "home.newest". * @param {object} definition State configuration object. */ this.state = state; function state(name, definition) { /*jshint validthis: true */ if (isObject(name)) definition = name; else definition.name = name; registerState(definition); return this; } /** * @ngdoc object * @name ui.router.state.$state * * @requires $rootScope * @requires $q * @requires ui.router.state.$view * @requires $injector * @requires ui.router.util.$resolve * @requires ui.router.state.$stateParams * * @property {object} params A param object, e.g. {sectionId: section.id)}, that * you'd like to test against the current active state. * @property {object} current A reference to the state's config object. However * you passed it in. Useful for accessing custom data. * @property {object} transition Currently pending transition. A promise that'll * resolve or reject. * * @description * `$state` service is responsible for representing states as well as transitioning * between them. It also provides interfaces to ask for current state or even states * you're coming from. */ // $urlRouter is injected just to ensure it gets instantiated this.$get = $get; $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$location', '$urlRouter', '$browser']; function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $location, $urlRouter, $browser) { var TransitionSuperseded = $q.reject(new Error('transition superseded')); var TransitionPrevented = $q.reject(new Error('transition prevented')); var TransitionAborted = $q.reject(new Error('transition aborted')); var TransitionFailed = $q.reject(new Error('transition failed')); var currentLocation = $location.url(); var baseHref = $browser.baseHref(); function syncUrl() { if ($location.url() !== currentLocation) { $location.url(currentLocation); $location.replace(); } } root.locals = { resolve: null, globals: { $stateParams: {} } }; $state = { params: {}, current: root.self, $current: root, transition: null }; /** * @ngdoc function * @name ui.router.state.$state#reload * @methodOf ui.router.state.$state * * @description * A method that force reloads the current state. All resolves are re-resolved, events are not re-fired, * and controllers reinstantiated (bug with controllers reinstantiating right now, fixing soon). * * @example * <pre> * var app angular.module('app', ['ui.router']); * * app.controller('ctrl', function ($scope, $state) { * $scope.reload = function(){ * $state.reload(); * } * }); * </pre> * * `reload()` is just an alias for: * <pre> * $state.transitionTo($state.current, $stateParams, { * reload: true, inherit: false, notify: false * }); * </pre> */ $state.reload = function reload() { $state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: false }); }; /** * @ngdoc function * @name ui.router.state.$state#go * @methodOf ui.router.state.$state * * @description * Convenience method for transitioning to a new state. `$state.go` calls * `$state.transitionTo` internally but automatically sets options to * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. * This allows you to easily use an absolute or relative to path and specify * only the parameters you'd like to update (while letting unspecified parameters * inherit from the currently active ancestor states). * * @example * <pre> * var app = angular.module('app', ['ui.router']); * * app.controller('ctrl', function ($scope, $state) { * $scope.changeState = function () { * $state.go('contact.detail'); * }; * }); * </pre> * <img src='../ngdoc_assets/StateGoExamples.png'/> * * @param {string} to Absolute state name or relative state path. Some examples: * * - `$state.go('contact.detail')` - will go to the `contact.detail` state * - `$state.go('^')` - will go to a parent state * - `$state.go('^.sibling')` - will go to a sibling state * - `$state.go('.child.grandchild')` - will go to grandchild state * * @param {object=} params A map of the parameters that will be sent to the state, * will populate $stateParams. Any parameters that are not specified will be inherited from currently * defined parameters. This allows, for example, going to a sibling state that shares parameters * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. * transitioning to a sibling will get you the parameters for all parents, transitioning to a child * will get you all current parameters, etc. * @param {object=} options Options object. The options are: * * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` * will not. If string, must be `"replace"`, which will update url and also replace last history record. * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), * defines which state to be relative from. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd * use this when you want to force a reload when *everything* is the same, including search params. * * @returns {promise} A promise representing the state of the new transition. * * Possible success values: * * - $state.current * * <br/>Possible rejection values: * * - 'transition superseded' - when a newer transition has been started after this one * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or * when a `$stateNotFound` `event.retry` promise errors. * - 'transition failed' - when a state has been unsuccessfully found after 2 tries. * - *resolve error* - when an error has occurred with a `resolve` * */ $state.go = function go(to, params, options) { return this.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options)); }; /** * @ngdoc function * @name ui.router.state.$state#transitionTo * @methodOf ui.router.state.$state * * @description * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go} * uses `transitionTo` internally. `$state.go` is recommended in most situations. * * @example * <pre> * var app = angular.module('app', ['ui.router']); * * app.controller('ctrl', function ($scope, $state) { * $scope.changeState = function () { * $state.transitionTo('contact.detail'); * }; * }); * </pre> * * @param {string} to State name. * @param {object=} toParams A map of the parameters that will be sent to the state, * will populate $stateParams. * @param {object=} options Options object. The options are: * * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` * will not. If string, must be `"replace"`, which will update url and also replace last history record. * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url. * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), * defines which state to be relative from. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd * use this when you want to force a reload when *everything* is the same, including search params. * * @returns {promise} A promise representing the state of the new transition. See * {@link ui.router.state.$state#methods_go $state.go}. */ $state.transitionTo = function transitionTo(to, toParams, options) { toParams = toParams || {}; options = extend({ location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false }, options || {}); var from = $state.$current, fromParams = $state.params, fromPath = from.path; var evt, toState = findState(to, options.relative); if (!isDefined(toState)) { // Broadcast not found event and abort the transition if prevented var redirect = { to: to, toParams: toParams, options: options }; /** * @ngdoc event * @name ui.router.state.$state#$stateNotFound * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired when a requested state **cannot be found** using the provided state name during transition. * The event is broadcast allowing any handlers a single chance to deal with the error (usually by * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler, * you can see its three properties in the example. You can use `event.preventDefault()` to abort the * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value. * * @param {Object} event Event object. * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties. * @param {State} fromState Current state object. * @param {Object} fromParams Current state params. * * @example * * <pre> * // somewhere, assume lazy.state has not been defined * $state.go("lazy.state", {a:1, b:2}, {inherit:false}); * * // somewhere else * $scope.$on('$stateNotFound', * function(event, unfoundState, fromState, fromParams){ * console.log(unfoundState.to); // "lazy.state" * console.log(unfoundState.toParams); // {a:1, b:2} * console.log(unfoundState.options); // {inherit:false} + default options * }) * </pre> */ evt = $rootScope.$broadcast('$stateNotFound', redirect, from.self, fromParams); if (evt.defaultPrevented) { syncUrl(); return TransitionAborted; } // Allow the handler to return a promise to defer state lookup retry if (evt.retry) { if (options.$retry) { syncUrl(); return TransitionFailed; } var retryTransition = $state.transition = $q.when(evt.retry); retryTransition.then(function() { if (retryTransition !== $state.transition) return TransitionSuperseded; redirect.options.$retry = true; return $state.transitionTo(redirect.to, redirect.toParams, redirect.options); }, function() { return TransitionAborted; }); syncUrl(); return retryTransition; } // Always retry once if the $stateNotFound was not prevented // (handles either redirect changed or state lazy-definition) to = redirect.to; toParams = redirect.toParams; options = redirect.options; toState = findState(to, options.relative); if (!isDefined(toState)) { if (options.relative) throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'"); throw new Error("No such state '" + to + "'"); } } if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'"); if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState); to = toState; var toPath = to.path; // Starting from the root of the path, keep all levels that haven't changed var keep, state, locals = root.locals, toLocals = []; for (keep = 0, state = toPath[keep]; state && state === fromPath[keep] && equalForKeys(toParams, fromParams, state.ownParams) && !options.reload; keep++, state = toPath[keep]) { locals = toLocals[keep] = state.locals; } // If we're going to the same state and all locals are kept, we've got nothing to do. // But clear 'transition', as we still want to cancel any other pending transitions. // TODO: We may not want to bump 'transition' if we're called from a location change that we've initiated ourselves, // because we might accidentally abort a legitimate transition initiated from code? if (shouldTriggerReload(to, from, locals, options) ) { if ( to.self.reloadOnSearch !== false ) syncUrl(); $state.transition = null; return $q.when($state.current); } // Normalize/filter parameters before we pass them to event handlers etc. toParams = normalize(to.params, toParams || {}); // Broadcast start event and cancel the transition if requested if (options.notify) { /** * @ngdoc event * @name ui.router.state.$state#$stateChangeStart * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired when the state transition **begins**. You can use `event.preventDefault()` * to prevent the transition from happening and then the transition promise will be * rejected with a `'transition prevented'` value. * * @param {Object} event Event object. * @param {State} toState The state being transitioned to. * @param {Object} toParams The params supplied to the `toState`. * @param {State} fromState The current state, pre-transition. * @param {Object} fromParams The params supplied to the `fromState`. * * @example * * <pre> * $rootScope.$on('$stateChangeStart', * function(event, toState, toParams, fromState, fromParams){ * event.preventDefault(); * // transitionTo() promise will be rejected with * // a 'transition prevented' error * }) * </pre> */ evt = $rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams); if (evt.defaultPrevented) { syncUrl(); return TransitionPrevented; } } // Resolve locals for the remaining states, but don't update any global state just // yet -- if anything fails to resolve the current state needs to remain untouched. // We also set up an inheritance chain for the locals here. This allows the view directive // to quickly look up the correct definition for each view in the current state. Even // though we create the locals object itself outside resolveState(), it is initially // empty and gets filled asynchronously. We need to keep track of the promise for the // (fully resolved) current locals, and pass this down the chain. var resolved = $q.when(locals); for (var l=keep; l<toPath.length; l++, state=toPath[l]) { locals = toLocals[l] = inherit(locals); resolved = resolveState(state, toParams, state===to, resolved, locals); } // Once everything is resolved, we are ready to perform the actual transition // and return a promise for the new state. We also keep track of what the // current promise is, so that we can detect overlapping transitions and // keep only the outcome of the last transition. var transition = $state.transition = resolved.then(function () { var l, entering, exiting; if ($state.transition !== transition) return TransitionSuperseded; // Exit 'from' states not kept for (l=fromPath.length-1; l>=keep; l--) { exiting = fromPath[l]; if (exiting.self.onExit) { $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals); } exiting.locals = null; } // Enter 'to' states not kept for (l=keep; l<toPath.length; l++) { entering = toPath[l]; entering.locals = toLocals[l]; if (entering.self.onEnter) { $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals); } } // Run it again, to catch any transitions in callbacks if ($state.transition !== transition) return TransitionSuperseded; // Update globals in $state $state.$current = to; $state.current = to.self; $state.params = toParams; copy($state.params, $stateParams); $state.transition = null; // Update $location var toNav = to.navigable; if (options.location && toNav) { $location.url(toNav.url.format(toNav.locals.globals.$stateParams)); if (options.location === 'replace') { $location.replace(); } } if (options.notify) { /** * @ngdoc event * @name ui.router.state.$state#$stateChangeSuccess * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired once the state transition is **complete**. * * @param {Object} event Event object. * @param {State} toState The state being transitioned to. * @param {Object} toParams The params supplied to the `toState`. * @param {State} fromState The current state, pre-transition. * @param {Object} fromParams The params supplied to the `fromState`. */ $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams); } currentLocation = $location.url(); return $state.current; }, function (error) { if ($state.transition !== transition) return TransitionSuperseded; $state.transition = null; /** * @ngdoc event * @name ui.router.state.$state#$stateChangeError * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired when an **error occurs** during transition. It's important to note that if you * have any errors in your resolve functions (javascript errors, non-existent services, etc) * they will not throw traditionally. You must listen for this $stateChangeError event to * catch **ALL** errors. * * @param {Object} event Event object. * @param {State} toState The state being transitioned to. * @param {Object} toParams The params supplied to the `toState`. * @param {State} fromState The current state, pre-transition. * @param {Object} fromParams The params supplied to the `fromState`. * @param {Error} error The resolve error object. */ $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error); syncUrl(); return $q.reject(error); }); return transition; }; /** * @ngdoc function * @name ui.router.state.$state#is * @methodOf ui.router.state.$state * * @description * Similar to {@link ui.router.state.$state#methods_includes $state.includes}, * but only checks for the full state name. If params is supplied then it will be * tested for strict equality against the current active params object, so all params * must match with none missing and no extras. * * @example * <pre> * $state.is('contact.details.item'); // returns true * $state.is(contactDetailItemStateObject); // returns true * * // everything else would return false * </pre> * * @param {string|object} stateName The state name or state object you'd like to check. * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like * to test against the current active state. * @returns {boolean} Returns true if it is the state. */ $state.is = function is(stateOrName, params) { var state = findState(stateOrName); if (!isDefined(state)) { return undefined; } if ($state.$current !== state) { return false; } return isDefined(params) && params !== null ? angular.equals($stateParams, params) : true; }; /** * @ngdoc function * @name ui.router.state.$state#includes * @methodOf ui.router.state.$state * * @description * A method to determine if the current active state is equal to or is the child of the * state stateName. If any params are passed then they will be tested for a match as well. * Not all the parameters need to be passed, just the ones you'd like to test for equality. * * @example * <pre> * $state.$current.name = 'contacts.details.item'; * * $state.includes("contacts"); // returns true * $state.includes("contacts.details"); // returns true * $state.includes("contacts.details.item"); // returns true * $state.includes("contacts.list"); // returns false * $state.includes("about"); // returns false * </pre> * * @description * Basic globing patterns will also work. * * @example * <pre> * $state.$current.name = 'contacts.details.item.url'; * * $state.includes("*.details.*.*"); // returns true * $state.includes("*.details.**"); // returns true * $state.includes("**.item.**"); // returns true * $state.includes("*.details.item.url"); // returns true * $state.includes("*.details.*.url"); // returns true * $state.includes("*.details.*"); // returns false * $state.includes("item.**"); // returns false * </pre> * * @param {string} stateOrName A partial name to be searched for within the current state name. * @param {object} params A param object, e.g. `{sectionId: section.id}`, * that you'd like to test against the current active state. * @returns {boolean} Returns true if it does include the state */ $state.includes = function includes(stateOrName, params) { if (isString(stateOrName) && isGlob(stateOrName)) { if (doesStateMatchGlob(stateOrName)) { stateOrName = $state.$current.name; } else { return false; } } var state = findState(stateOrName); if (!isDefined(state)) { return undefined; } if (!isDefined($state.$current.includes[state.name])) { return false; } var validParams = true; angular.forEach(params, function(value, key) { if (!isDefined($stateParams[key]) || $stateParams[key] !== value) { validParams = false; } }); return validParams; }; /** * @ngdoc function * @name ui.router.state.$state#href * @methodOf ui.router.state.$state * * @description * A url generation method that returns the compiled url for the given state populated with the given params. * * @example * <pre> * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob"); * </pre> * * @param {string|object} stateOrName The state name or state object you'd like to generate a url from. * @param {object=} params An object of parameter values to fill the state's required parameters. * @param {object=} options Options object. The options are: * * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the * first parameter, then the constructed href url will be built from the first navigable ancestor (aka * ancestor with a valid url). * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), * defines which state to be relative from. * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". * * @returns {string} compiled state url */ $state.href = function href(stateOrName, params, options) { options = extend({ lossy: true, inherit: false, absolute: false, relative: $state.$current }, options || {}); var state = findState(stateOrName, options.relative); if (!isDefined(state)) return null; params = inheritParams($stateParams, params || {}, $state.$current, state); var nav = (state && options.lossy) ? state.navigable : state; var url = (nav && nav.url) ? nav.url.format(normalize(state.params, params || {})) : null; if (!$locationProvider.html5Mode() && url) { url = "#" + $locationProvider.hashPrefix() + url; } if (baseHref !== '/') { if ($locationProvider.html5Mode()) { url = baseHref.slice(0, -1) + url; } else if (options.absolute){ url = baseHref.slice(1) + url; } } if (options.absolute && url) { url = $location.protocol() + '://' + $location.host() + ($location.port() == 80 || $location.port() == 443 ? '' : ':' + $location.port()) + (!$locationProvider.html5Mode() && url ? '/' : '') + url; } return url; }; /** * @ngdoc function * @name ui.router.state.$state#get * @methodOf ui.router.state.$state * * @description * Returns the state configuration object for any specific state or all states. * * @param {string|object=} stateOrName If provided, will only get the config for * the requested state. If not provided, returns an array of ALL state configs. * @returns {object|array} State configuration object or array of all objects. */ $state.get = function (stateOrName, context) { if (!isDefined(stateOrName)) { var list = []; forEach(states, function(state) { list.push(state.self); }); return list; } var state = findState(stateOrName, context); return (state && state.self) ? state.self : null; }; function resolveState(state, params, paramsAreFiltered, inherited, dst) { // Make a restricted $stateParams with only the parameters that apply to this state if // necessary. In addition to being available to the controller and onEnter/onExit callbacks, // we also need $stateParams to be available for any $injector calls we make during the // dependency resolution process. var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params, params); var locals = { $stateParams: $stateParams }; // Resolve 'global' dependencies for the state, i.e. those not specific to a view. // We're also including $stateParams in this; that way the parameters are restricted // to the set that should be visible to the state, and are independent of when we update // the global $state and $stateParams values. dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state); var promises = [ dst.resolve.then(function (globals) { dst.globals = globals; }) ]; if (inherited) promises.push(inherited); // Resolve template and dependencies for all views. forEach(state.views, function (view, name) { var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {}); injectables.$template = [ function () { return $view.load(name, { view: view, locals: locals, params: $stateParams, notify: false }) || ''; }]; promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) { // References to the controller (only instantiated at link time) if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) { var injectLocals = angular.extend({}, injectables, locals); result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals); } else { result.$$controller = view.controller; } // Provide access to the state itself for internal use result.$$state = state; dst[name] = result; })); }); // Wait for all the promises and then return the activation object return $q.all(promises).then(function (values) { return dst; }); } return $state; } function shouldTriggerReload(to, from, locals, options) { if ( to === from && ((locals === from.locals && !options.reload) || (to.self.reloadOnSearch === false)) ) { return true; } } } angular.module('ui.router.state') .value('$stateParams', {}) .provider('$state', $StateProvider);
{ "content_hash": "3f1566588856f9dcb6750458cc68921d", "timestamp": "", "source": "github", "line_count": 1203, "max_line_length": 127, "avg_line_length": 40.771404821280136, "alnum_prop": 0.6183330614907845, "repo_name": "HabitRPG/ui-router", "id": "c49932935374a74e77173bcbc6131d8ca3f27074", "size": "49052", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/state.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "741" }, { "name": "JavaScript", "bytes": "268061" } ], "symlink_target": "" }
namespace chromeos { // A fake implementation of ShillDeviceClient. // Implemented: Stub cellular device for SMS testing. class CHROMEOS_EXPORT FakeShillDeviceClient : public ShillDeviceClient, public ShillDeviceClient::TestInterface { public: FakeShillDeviceClient(); virtual ~FakeShillDeviceClient(); // ShillDeviceClient overrides virtual void Init(dbus::Bus* bus) OVERRIDE; virtual void AddPropertyChangedObserver( const dbus::ObjectPath& device_path, ShillPropertyChangedObserver* observer) OVERRIDE; virtual void RemovePropertyChangedObserver( const dbus::ObjectPath& device_path, ShillPropertyChangedObserver* observer) OVERRIDE; virtual void GetProperties(const dbus::ObjectPath& device_path, const DictionaryValueCallback& callback) OVERRIDE; virtual void ProposeScan(const dbus::ObjectPath& device_path, const VoidDBusMethodCallback& callback) OVERRIDE; virtual void SetProperty(const dbus::ObjectPath& device_path, const std::string& name, const base::Value& value, const base::Closure& callback, const ErrorCallback& error_callback) OVERRIDE; virtual void ClearProperty(const dbus::ObjectPath& device_path, const std::string& name, const VoidDBusMethodCallback& callback) OVERRIDE; virtual void AddIPConfig( const dbus::ObjectPath& device_path, const std::string& method, const ObjectPathDBusMethodCallback& callback) OVERRIDE; virtual void RequirePin(const dbus::ObjectPath& device_path, const std::string& pin, bool require, const base::Closure& callback, const ErrorCallback& error_callback) OVERRIDE; virtual void EnterPin(const dbus::ObjectPath& device_path, const std::string& pin, const base::Closure& callback, const ErrorCallback& error_callback) OVERRIDE; virtual void UnblockPin(const dbus::ObjectPath& device_path, const std::string& puk, const std::string& pin, const base::Closure& callback, const ErrorCallback& error_callback) OVERRIDE; virtual void ChangePin(const dbus::ObjectPath& device_path, const std::string& old_pin, const std::string& new_pin, const base::Closure& callback, const ErrorCallback& error_callback) OVERRIDE; virtual void Register(const dbus::ObjectPath& device_path, const std::string& network_id, const base::Closure& callback, const ErrorCallback& error_callback) OVERRIDE; virtual void SetCarrier(const dbus::ObjectPath& device_path, const std::string& carrier, const base::Closure& callback, const ErrorCallback& error_callback) OVERRIDE; virtual void Reset(const dbus::ObjectPath& device_path, const base::Closure& callback, const ErrorCallback& error_callback) OVERRIDE; virtual void PerformTDLSOperation( const dbus::ObjectPath& device_path, const std::string& operation, const std::string& peer, const StringCallback& callback, const ErrorCallback& error_callback) OVERRIDE; virtual ShillDeviceClient::TestInterface* GetTestInterface() OVERRIDE; // ShillDeviceClient::TestInterface overrides. virtual void AddDevice(const std::string& device_path, const std::string& type, const std::string& object_path) OVERRIDE; virtual void RemoveDevice(const std::string& device_path) OVERRIDE; virtual void ClearDevices() OVERRIDE; virtual void SetDeviceProperty(const std::string& device_path, const std::string& name, const base::Value& value) OVERRIDE; virtual std::string GetDevicePathForType(const std::string& type) OVERRIDE; void set_tdls_busy_count(int count) { tdls_busy_count_ = count; } private: typedef ObserverList<ShillPropertyChangedObserver> PropertyObserverList; void SetDefaultProperties(); void PassStubDeviceProperties(const dbus::ObjectPath& device_path, const DictionaryValueCallback& callback) const; // Posts a task to run a void callback with status code |status|. void PostVoidCallback(const VoidDBusMethodCallback& callback, DBusMethodCallStatus status); void NotifyObserversPropertyChanged(const dbus::ObjectPath& device_path, const std::string& property); base::DictionaryValue* GetDeviceProperties(const std::string& device_path); PropertyObserverList& GetObserverList(const dbus::ObjectPath& device_path); // Dictionary of <device_name, Dictionary>. base::DictionaryValue stub_devices_; // Observer list for each device. std::map<dbus::ObjectPath, PropertyObserverList*> observer_list_; int tdls_busy_count_; // Number of times to return InProgress for TDLS. // Note: This should remain the last member so it'll be destroyed and // invalidate its weak pointers before any other members are destroyed. base::WeakPtrFactory<FakeShillDeviceClient> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(FakeShillDeviceClient); }; } // namespace chromeos #endif // CHROMEOS_DBUS_FAKE_SHILL_DEVICE_CLIENT_H_
{ "content_hash": "ec30735882e5448c9bcd83f3699c71cf", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 79, "avg_line_length": 48.041666666666664, "alnum_prop": 0.6411101474414571, "repo_name": "ChromiumWebApps/chromium", "id": "ac8f565463397630aad519408faa875c01de9eb8", "size": "6166", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "chromeos/dbus/fake_shill_device_client.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "52960" }, { "name": "Awk", "bytes": "8660" }, { "name": "C", "bytes": "42286199" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "198616766" }, { "name": "CSS", "bytes": "937333" }, { "name": "DOT", "bytes": "2984" }, { "name": "Java", "bytes": "5695686" }, { "name": "JavaScript", "bytes": "21967126" }, { "name": "M", "bytes": "2190" }, { "name": "Matlab", "bytes": "2262" }, { "name": "Objective-C", "bytes": "7602057" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "1210885" }, { "name": "Python", "bytes": "10774996" }, { "name": "R", "bytes": "262" }, { "name": "Shell", "bytes": "1316721" }, { "name": "Tcl", "bytes": "277091" }, { "name": "TypeScript", "bytes": "1560024" }, { "name": "XSLT", "bytes": "13493" }, { "name": "nesC", "bytes": "15243" } ], "symlink_target": "" }
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Linking_Charities.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
{ "content_hash": "c4008e0a87f59353ce9b0c351675540d", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 81, "avg_line_length": 37.76190476190476, "alnum_prop": 0.6242118537200504, "repo_name": "linkingcharities/linkingcharities", "id": "96ae664aa583a19c17aa6470f7fe268dd9f8438e", "size": "815", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Linking_Charities/manage.py", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "28" }, { "name": "HTML", "bytes": "6023" }, { "name": "Makefile", "bytes": "124" }, { "name": "Python", "bytes": "68704" }, { "name": "Shell", "bytes": "182" } ], "symlink_target": "" }
from setuptools import setup setup( name="pep518_twin_forkbombs_second", version="238", py_modules=["pep518_twin_forkbombs_second"], )
{ "content_hash": "b715daae54c8750c70c8af8c3b8083f6", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 48, "avg_line_length": 21.142857142857142, "alnum_prop": 0.6959459459459459, "repo_name": "pypa/pip", "id": "c14c1cfb0259789ab547e61517c6d6a26568b23f", "size": "148", "binary": false, "copies": "4", "ref": "refs/heads/main", "path": "tests/data/src/pep518_twin_forkbombs_second-238/setup.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3137" }, { "name": "PowerShell", "bytes": "2137" }, { "name": "Python", "bytes": "7137503" } ], "symlink_target": "" }
package kops import ( "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) type Cluster struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec ClusterSpec `json:"spec,omitempty"` } type ClusterList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []Cluster `json:"items"` } type ClusterSpec struct { // The Channel we are following Channel string `json:"channel,omitempty"` // ConfigBase is the path where we store configuration for the cluster // This might be different that the location when the cluster spec itself is stored, // both because this must be accessible to the cluster, // and because it might be on a different cloud or storage system (etcd vs S3) ConfigBase string `json:"configBase,omitempty"` // The CloudProvider to use (aws or gce) CloudProvider string `json:"cloudProvider,omitempty"` // The version of kubernetes to install (optional, and can be a "spec" like stable) KubernetesVersion string `json:"kubernetesVersion,omitempty"` //// The Node initializer technique to use: cloudinit or nodeup //NodeInit string `json:",omitempty"` // Configuration of subnets we are targeting Subnets []ClusterSubnetSpec `json:"subnets,omitempty"` // Project is the cloud project we should use, required on GCE Project string `json:"project,omitempty"` // MasterPublicName is the external DNS name for the master nodes MasterPublicName string `json:"masterPublicName,omitempty"` // MasterInternalName is the internal DNS name for the master nodes MasterInternalName string `json:"masterInternalName,omitempty"` // The CIDR used for the AWS VPC / GCE Network, or otherwise allocated to k8s // This is a real CIDR, not the internal k8s network NetworkCIDR string `json:"networkCIDR,omitempty"` // NetworkID is an identifier of a network, if we want to reuse/share an existing network (e.g. an AWS VPC) NetworkID string `json:"networkID,omitempty"` // Topology defines the type of network topology to use on the cluster - default public // This is heavily weighted towards AWS for the time being, but should also be agnostic enough // to port out to GCE later if needed Topology *TopologySpec `json:"topology,omitempty"` // SecretStore is the VFS path to where secrets are stored SecretStore string `json:"secretStore,omitempty"` // KeyStore is the VFS path to where SSL keys and certificates are stored KeyStore string `json:"keyStore,omitempty"` // ConfigStore is the VFS path to where the configuration (Cluster, InstanceGroups etc) is stored ConfigStore string `json:"configStore,omitempty"` // DNSZone is the DNS zone we should use when configuring DNS // This is because some clouds let us define a managed zone foo.bar, and then have // kubernetes.dev.foo.bar, without needing to define dev.foo.bar as a hosted zone. // DNSZone will probably be a suffix of the MasterPublicName and MasterInternalName // Note that DNSZone can either by the host name of the zone (containing dots), // or can be an identifier for the zone. DNSZone string `json:"dnsZone,omitempty"` // ClusterDNSDomain is the suffix we use for internal DNS names (normally cluster.local) ClusterDNSDomain string `json:"clusterDNSDomain,omitempty"` //InstancePrefix string `json:",omitempty"` // ClusterName is a unique identifier for the cluster, and currently must be a DNS name //ClusterName string `json:",omitempty"` //ClusterIPRange string `json:",omitempty"` // ServiceClusterIPRange is the CIDR, from the internal network, where we allocate IPs for services ServiceClusterIPRange string `json:"serviceClusterIPRange,omitempty"` //MasterIPRange string `json:",omitempty"` // NonMasqueradeCIDR is the CIDR for the internal k8s network (on which pods & services live) // It cannot overlap ServiceClusterIPRange NonMasqueradeCIDR string `json:"nonMasqueradeCIDR,omitempty"` // SSHAccess is a list of the CIDRs that can access SSH. SSHAccess []string `json:"sshAccess,omitempty"` // KubernetesAPIAccess is a list of the CIDRs that can access the Kubernetes API endpoint (master HTTPS) KubernetesAPIAccess []string `json:"kubernetesApiAccess,omitempty"` // IsolatesMasters determines whether we should lock down masters so that they are not on the pod network. // true is the kube-up behaviour, but it is very surprising: it means that daemonsets only work on the master // if they have hostNetwork=true. // false is now the default, and it will: // * give the master a normal PodCIDR // * run kube-proxy on the master // * enable debugging handlers on the master, so kubectl logs works IsolateMasters *bool `json:"isolateMasters,omitempty"` // UpdatePolicy determines the policy for applying upgrades automatically. // Valid values: // 'external' do not apply updates automatically - they are applied manually or by an external system // missing: default policy (currently OS security upgrades that do not require a reboot) UpdatePolicy *string `json:"updatePolicy,omitempty"` // Additional policies to add for roles AdditionalPolicies *map[string]string `json:"additionalPolicies,omitempty"` //HairpinMode string `json:",omitempty"` // //OpencontrailTag string `json:",omitempty"` //OpencontrailKubernetesTag string `json:",omitempty"` //OpencontrailPublicSubnet string `json:",omitempty"` // //EnableClusterMonitoring string `json:",omitempty"` //EnableL7LoadBalancing string `json:",omitempty"` //EnableClusterUI *bool `json:",omitempty"` // //EnableClusterDNS *bool `json:",omitempty"` //DNSReplicas int `json:",omitempty"` //DNSServerIP string `json:",omitempty"` //EnableClusterLogging *bool `json:",omitempty"` //EnableNodeLogging *bool `json:",omitempty"` //LoggingDestination string `json:",omitempty"` //ElasticsearchLoggingReplicas int `json:",omitempty"` // //EnableClusterRegistry *bool `json:",omitempty"` //ClusterRegistryDisk string `json:",omitempty"` //ClusterRegistryDiskSize int `json:",omitempty"` // //EnableCustomMetrics *bool `json:",omitempty"` // //RegisterMasterKubelet *bool `json:",omitempty"` //// Image is the default image spec to use for the cluster //Image string `json:",omitempty"` //KubeUser string `json:",omitempty"` // //// These are moved to CAStore / SecretStore ////KubePassword string ////KubeletToken string ////KubeProxyToken string ////BearerToken string ////CACert []byte ////CAKey []byte ////KubeletCert []byte ////KubeletKey []byte ////MasterCert []byte ////MasterKey []byte ////KubecfgCert []byte ////KubecfgKey []byte // //AdmissionControl string `json:",omitempty"` // //KubeImageTag string `json:",omitempty"` //KubeDockerRegistry string `json:",omitempty"` //KubeAddonRegistry string `json:",omitempty"` // //KubeletPort int `json:",omitempty"` // //KubeApiserverRequestTimeout int `json:",omitempty"` // //TerminatedPodGcThreshold string `json:",omitempty"` // //EnableManifestURL *bool `json:",omitempty"` //ManifestURL string `json:",omitempty"` //ManifestURLHeader string `json:",omitempty"` // //TestCluster string `json:",omitempty"` // //E2EStorageTestEnvironment string `json:",omitempty"` //KubeletTestArgs string `json:",omitempty"` //KubeletTestLogLevel string `json:",omitempty"` //DockerTestArgs string `json:",omitempty"` //DockerTestLogLevel string `json:",omitempty"` //ApiserverTestArgs string `json:",omitempty"` //ApiserverTestLogLevel string `json:",omitempty"` //ControllerManagerTestArgs string `json:",omitempty"` //ControllerManagerTestLogLevel string `json:",omitempty"` //SchedulerTestArgs string `json:",omitempty"` //SchedulerTestLogLevel string `json:",omitempty"` //KubeProxyTestArgs string `json:",omitempty"` //KubeProxyTestLogLevel string `json:",omitempty"` //// Masters is the configuration for each master in the cluster //Masters []*MasterConfig `json:",omitempty"` // EtcdClusters stores the configuration for each cluster EtcdClusters []*EtcdClusterSpec `json:"etcdClusters,omitempty"` // Component configurations Docker *DockerConfig `json:"docker,omitempty"` KubeDNS *KubeDNSConfig `json:"kubeDNS,omitempty"` KubeAPIServer *KubeAPIServerConfig `json:"kubeAPIServer,omitempty"` KubeControllerManager *KubeControllerManagerConfig `json:"kubeControllerManager,omitempty"` KubeScheduler *KubeSchedulerConfig `json:"kubeScheduler,omitempty"` KubeProxy *KubeProxyConfig `json:"kubeProxy,omitempty"` Kubelet *KubeletConfigSpec `json:"kubelet,omitempty"` MasterKubelet *KubeletConfigSpec `json:"masterKubelet,omitempty"` CloudConfig *CloudConfiguration `json:"cloudConfig,omitempty"` // Networking configuration Networking *NetworkingSpec `json:"networking,omitempty"` // API field controls how the API is exposed outside the cluster API *AccessSpec `json:"api,omitempty"` // Authorization field controls how the cluster is configured for authorization Authorization *AuthorizationSpec `json:"authorization,omitempty"` // Tags for AWS instance groups CloudLabels map[string]string `json:"cloudLabels,omitempty"` // Hooks for custom actions e.g. on first installation Hooks []HookSpec `json:"hooks,omitempty"` } type HookSpec struct { ExecContainer *ExecContainerAction `json:"execContainer,omitempty"` } type ExecContainerAction struct { // Docker image name. Image string `json:"image,omitempty" ` Command []string `json:"command,omitempty"` } type AuthorizationSpec struct { AlwaysAllow *AlwaysAllowAuthorizationSpec `json:"alwaysAllow,omitempty"` RBAC *RBACAuthorizationSpec `json:"rbac,omitempty"` } func (s *AuthorizationSpec) IsEmpty() bool { return s.RBAC == nil && s.AlwaysAllow == nil } type RBACAuthorizationSpec struct { } type AlwaysAllowAuthorizationSpec struct { } type AccessSpec struct { DNS *DNSAccessSpec `json:"dns,omitempty"` LoadBalancer *LoadBalancerAccessSpec `json:"loadBalancer,omitempty"` } func (s *AccessSpec) IsEmpty() bool { return s.DNS == nil && s.LoadBalancer == nil } type DNSAccessSpec struct { } // LoadBalancerType string describes LoadBalancer types (public, internal) type LoadBalancerType string const ( LoadBalancerTypePublic LoadBalancerType = "Public" LoadBalancerTypeInternal LoadBalancerType = "Internal" ) type LoadBalancerAccessSpec struct { Type LoadBalancerType `json:"type,omitempty"` IdleTimeoutSeconds *int64 `json:"idleTimeoutSeconds,omitempty"` } type KubeDNSConfig struct { // Image is the name of the docker image to run Image string `json:"image,omitempty"` Replicas int `json:"replicas,omitempty"` Domain string `json:"domain,omitempty"` ServerIP string `json:"serverIP,omitempty"` } type EtcdClusterSpec struct { // Name is the name of the etcd cluster (main, events etc) Name string `json:"name,omitempty"` // EtcdMember stores the configurations for each member of the cluster (including the data volume) Members []*EtcdMemberSpec `json:"etcdMembers,omitempty"` } type EtcdMemberSpec struct { // Name is the name of the member within the etcd cluster Name string `json:"name,omitempty"` InstanceGroup *string `json:"instanceGroup,omitempty"` VolumeType *string `json:"volumeType,omitempty"` VolumeSize *int32 `json:"volumeSize,omitempty"` KmsKeyId *string `json:"kmsKeyId,omitempty"` EncryptedVolume *bool `json:"encryptedVolume,omitempty"` } // SubnetType string describes subnet types (public, private, utility) type SubnetType string const ( SubnetTypePublic SubnetType = "Public" SubnetTypePrivate SubnetType = "Private" SubnetTypeUtility SubnetType = "Utility" ) type ClusterSubnetSpec struct { Name string `json:"name,omitempty"` Zone string `json:"zone,omitempty"` CIDR string `json:"cidr,omitempty"` // ProviderID is the cloud provider id for the objects associated with the zone (the subnet on AWS) ProviderID string `json:"id,omitempty"` Egress string `json:"egress,omitempty"` Type SubnetType `json:"type,omitempty"` } // FillDefaults populates default values. // This is different from PerformAssignments, because these values are changeable, and thus we don't need to // store them (i.e. we don't need to 'lock them') func (c *Cluster) FillDefaults() error { // Topology support if c.Spec.Topology == nil { c.Spec.Topology = &TopologySpec{Masters: TopologyPublic, Nodes: TopologyPublic} c.Spec.Topology.DNS = &DNSSpec{Type: DNSTypePublic} } if c.Spec.Networking == nil { c.Spec.Networking = &NetworkingSpec{} } // TODO move this into networking.go :( if c.Spec.Networking.Classic != nil { // OK } else if c.Spec.Networking.Kubenet != nil { // OK } else if c.Spec.Networking.CNI != nil { // OK } else if c.Spec.Networking.External != nil { // OK } else if c.Spec.Networking.Kopeio != nil { // OK } else if c.Spec.Networking.Weave != nil { // OK } else if c.Spec.Networking.Flannel != nil { // OK } else if c.Spec.Networking.Calico != nil { // OK } else if c.Spec.Networking.Canal != nil { // OK } else { // No networking model selected; choose Kubenet c.Spec.Networking.Kubenet = &KubenetNetworkingSpec{} } if c.Spec.Channel == "" { c.Spec.Channel = DefaultChannel } if c.ObjectMeta.Name == "" { return fmt.Errorf("cluster Name not set in FillDefaults") } if c.Spec.MasterInternalName == "" { c.Spec.MasterInternalName = "api.internal." + c.ObjectMeta.Name } if c.Spec.MasterPublicName == "" { c.Spec.MasterPublicName = "api." + c.ObjectMeta.Name } return nil } // SharedVPC is a simple helper function which makes the templates for a shared VPC clearer func (c *Cluster) SharedVPC() bool { return c.Spec.NetworkID != "" }
{ "content_hash": "f034bd39e9ebe06b0bf48de7b412f488", "timestamp": "", "source": "github", "line_count": 398, "max_line_length": 110, "avg_line_length": 36.87688442211055, "alnum_prop": 0.6938747700483751, "repo_name": "sethpollack/kops", "id": "eea7a2199b56efb86fba1b40d881d488b2105a40", "size": "15246", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "pkg/apis/kops/cluster.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "2639484" }, { "name": "HCL", "bytes": "215517" }, { "name": "Makefile", "bytes": "19099" }, { "name": "Protocol Buffer", "bytes": "611" }, { "name": "Python", "bytes": "15199" }, { "name": "Ruby", "bytes": "1027" }, { "name": "Shell", "bytes": "26022" } ], "symlink_target": "" }
package io import ( "github.com/ipfs/go-ipfs/Godeps/_workspace/src/code.google.com/p/gogoprotobuf/proto" "io" ) func NewFullWriter(w io.Writer) WriteCloser { return &fullWriter{w, nil} } type fullWriter struct { w io.Writer buffer []byte } func (this *fullWriter) WriteMsg(msg proto.Message) (err error) { var data []byte if m, ok := msg.(marshaler); ok { n := m.Size() if n >= len(this.buffer) { this.buffer = make([]byte, n) } _, err = m.MarshalTo(this.buffer) if err != nil { return err } data = this.buffer[:n] } else { data, err = proto.Marshal(msg) if err != nil { return err } } _, err = this.w.Write(data) return err } func (this *fullWriter) Close() error { if closer, ok := this.w.(io.Closer); ok { return closer.Close() } return nil } type fullReader struct { r io.Reader buf []byte } func NewFullReader(r io.Reader, maxSize int) ReadCloser { return &fullReader{r, make([]byte, maxSize)} } func (this *fullReader) ReadMsg(msg proto.Message) error { length, err := this.r.Read(this.buf) if err != nil { return err } return proto.Unmarshal(this.buf[:length], msg) } func (this *fullReader) Close() error { if closer, ok := this.r.(io.Closer); ok { return closer.Close() } return nil }
{ "content_hash": "14fca261922dcc0f15f1ca8034e86f69", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 85, "avg_line_length": 18.66176470588235, "alnum_prop": 0.6461780929866037, "repo_name": "torarnv/go-ipfs", "id": "4cccb01495934bbe92ab2cc5057ea68a1506c0fb", "size": "2767", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Godeps/_workspace/src/code.google.com/p/gogoprotobuf/io/full.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "1329178" }, { "name": "Makefile", "bytes": "7029" }, { "name": "Protocol Buffer", "bytes": "5773" }, { "name": "PureBasic", "bytes": "29" }, { "name": "Python", "bytes": "788" }, { "name": "Shell", "bytes": "58447" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX Morph XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #include "allocacheck.h" // for alloca /*****************************************************************************/ // Split a tree at the given point // -- Introduces a new temporary variable // -- evaluates *splitPoint into the new temp, in a new statement inserted before 'stmt' // -- substitutes the temporary for '*splitPoint' in 'stmt' // '*splitpoint' must be a node in 'stmt', which is within 'blk', and 'splitpoint' is a pointer // to the link to that node, contained in its parent node. GenTree* Compiler::fgMorphSplitTree(GenTree** splitPoint, // where to split GenTree* stmt, // top level statement housing this tree BasicBlock* blk) // block we are in { GenTree* newTree; GenTree* temp; if ((*splitPoint)->OperIsAssignment()) { // it's already being assigned so don't introduce a new one newTree = *splitPoint; temp = (*splitPoint)->gtGetOp1(); } else { unsigned lclNum = lvaGrabTemp(true DEBUGARG("split tree")); newTree = gtNewTempAssign(lclNum, *splitPoint); temp = gtNewLclvNode(lclNum, (*splitPoint)->TypeGet()); } GenTreePtr asg = gtNewStmt(newTree); *splitPoint = temp; fgInsertStmtBefore(blk, stmt, asg); return asg; } // state carried over the tree walk, to be used in making // a splitting decision. struct SplitData { // number of calls seen size_t count; // callback to determine if we should split here Compiler::fgSplitPredicate* pred; // root stmt of tree being processed GenTree* root; }; #ifdef _TARGET_ARM_ // Returns true if we should split the tree above this node. // For ARM FP, handling multiple calls per tree via a local and // greedy register allocator could result in a lot of shuffling. // So let the global register allocator handle these cases. bool shouldSplitARM(GenTree* tree, GenTree* parent, Compiler::fgWalkData* data) { if (tree->IsCall() && varTypeIsFloating(tree) && parent && !parent->OperIsAssignment()) { // increment call count SplitData* tmpState = (SplitData*) data->pCallbackData; tmpState->count++; return tmpState->count > 1; } else { return false; } } #endif // _TARGET_ARM_ // Callback for the tree walker, called once per node. // Determines if we want to split, performs the split, and then processes the rest of the tree Compiler::fgWalkResult Compiler::fgSplitHelper(GenTree** ppTree, fgWalkData* data) { GenTree* tree = *ppTree; Compiler* comp = data->compiler; SplitData* tmpState = (SplitData*) data->pCallbackData; fgSplitPredicate* pred = tmpState->pred; if (pred(tree, data->parent, data)) // does this look like somewhere we want to split? { //printf("tmpstate2 = %d %p r:%p tmp:%p tree:%p\n", tmpState->count, tmpState->pred, tmpState->root, tmpState, tree); GenTree* result = comp->fgMorphSplitTree(ppTree, tmpState->root, comp->compCurBB); GenTree* oldStatement = comp->compCurStmt; comp->compCurStmt = result; // because we are doing this in pre-order we also have to process // the subtree that we have just split off comp->fgSplitProcessOneTree(result, pred); // restore it comp->compCurStmt = oldStatement; return Compiler::WALK_SKIP_SUBTREES; } //else printf("tmpstate3 = %d %p r:%p tmp:%p tree:%p\n", tmpState->count, tmpState->pred, tmpState->root, tmpState, tree); return Compiler::WALK_CONTINUE; } void Compiler::fgSplitProcessOneTree(GenTree* tree, fgSplitPredicate pred) { SplitData tmpState = {0}; tmpState.pred = pred; tmpState.root = tree; fgWalkTreePre(&(tree->gtStmt.gtStmtExpr), fgSplitHelper, (void*) &tmpState); } // Split expression trees at points which in the case of ARM this is done. void Compiler::fgSplitMethodTrees(void) { #ifndef _TARGET_ARM_ return; #else // _TARGET_ARM_ for (BasicBlock* block = fgFirstBB; block; block = block->bbNext) { compCurBB = block; for (GenTree* tree = block->bbTreeList; tree; tree = tree->gtNext) { assert(tree != tree->gtNext); fgSplitProcessOneTree(tree, shouldSplitARM); } } #endif // _TARGET_ARM_ } // Convert the given node into a call to the specified helper passing // the given argument list. // Tries to fold constants and also adds an edge for overflow exception // returns the morphed tree GenTreePtr Compiler::fgMorphCastIntoHelper(GenTreePtr tree, int helper, GenTreePtr oper) { GenTree *result; /* If the operand is a constant, we'll try to fold it */ if (oper->OperIsConst()) { GenTreePtr oldTree = tree; tree = gtFoldExprConst(tree); // This may not fold the constant (NaN ...) if (tree != oldTree) return fgMorphTree(tree); else if (tree->OperKind() & GTK_CONST) return fgMorphConst(tree); // assert that oper is unchanged and that it is still a GT_CAST node noway_assert(tree->gtCast.CastOp() == oper); noway_assert(tree->gtOper == GT_CAST); } result = fgMorphIntoHelperCall(tree, helper, gtNewArgList(oper)); assert(result == tree); return result; } /***************************************************************************** * * Convert the given node into a call to the specified helper passing * the given argument list. */ GenTreePtr Compiler::fgMorphIntoHelperCall(GenTreePtr tree, int helper, GenTreeArgList* args) { tree->ChangeOper(GT_CALL); tree->gtFlags |= GTF_CALL; tree->gtCall.gtCallType = CT_HELPER; tree->gtCall.gtCallMethHnd = eeFindHelper(helper); tree->gtCall.gtCallArgs = args; tree->gtCall.gtCallObjp = NULL; tree->gtCall.gtCallLateArgs = NULL; tree->gtCall.fgArgInfo = NULL; tree->gtCall.gtRetClsHnd = NULL; tree->gtCall.gtCallRegUsedMask = RBM_NONE; tree->gtCall.gtCallMoreFlags = 0; tree->gtCall.gtInlineCandidateInfo = NULL; tree->gtCall.gtControlExpr = NULL; #ifdef FEATURE_READYTORUN_COMPILER tree->gtCall.gtEntryPoint.addr = nullptr; #endif /* Perform the morphing */ tree = fgMorphArgs(tree->AsCall()); return tree; } /***************************************************************************** * This node should not be referenced by anyone now. Set its values to garbage * to catch extra references */ inline void DEBUG_DESTROY_NODE(GenTreePtr tree) { #ifdef DEBUG // printf("DEBUG_DESTROY_NODE for [0x%08x]\n", tree); // Save gtOper in case we want to find out what this node was tree->gtOperSave = tree->gtOper; tree->gtType = TYP_UNDEF; tree->gtFlags |= 0xFFFFFFFF & ~GTF_NODE_MASK; if (tree->OperIsSimple()) { tree->gtOp.gtOp1 = tree->gtOp.gtOp2 = NULL; } // Must do this last, because the "gtOp" check above will fail otherwise. // Don't call SetOper, because GT_COUNT is not a valid value tree->gtOper = GT_COUNT; #endif } /***************************************************************************** * * Determine if a relop must be morphed to a qmark to manifest a boolean value. * This is done when code generation can't create straight-line code to do it. */ bool Compiler::fgMorphRelopToQmark(GenTreePtr tree) { #ifndef LEGACY_BACKEND return false; #else // LEGACY_BACKEND return (genActualType(tree->TypeGet()) == TYP_LONG) || varTypeIsFloating(tree->TypeGet()); #endif // LEGACY_BACKEND } /***************************************************************************** * * Morph a cast node (we perform some very simple transformations here). */ #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:21000) // Suppress PREFast warning about overly large function #endif GenTreePtr Compiler::fgMorphCast(GenTreePtr tree) { noway_assert(tree->gtOper == GT_CAST); noway_assert(genTypeSize(TYP_I_IMPL) == sizeof(void*)); /* The first sub-operand is the thing being cast */ GenTreePtr oper = tree->gtCast.CastOp(); var_types srcType = genActualType(oper->TypeGet()); unsigned srcSize; var_types dstType = tree->CastToType(); unsigned dstSize = genTypeSize(dstType); // See if the cast has to be done in two steps. R -> I if (varTypeIsFloating(srcType) && varTypeIsIntegral(dstType)) { // Only x86 must go through TYP_DOUBLE to get to all // integral types everybody else can get straight there // except for when using helpers if (srcType == TYP_FLOAT #if !FEATURE_STACK_FP_X87 #if defined(_TARGET_ARM64_) // Amd64: src = float, dst is overflow conversion. // This goes through helper and hence src needs to be converted to double. && tree->gtOverflow() #elif defined(_TARGET_AMD64_) // Amd64: src = float, dst = uint64 or overflow conversion. // This goes through helper and hence src needs to be converted to double. && (tree->gtOverflow() || (dstType == TYP_ULONG)) #elif defined(_TARGET_ARM_) // Arm: src = float, dst = int64/uint64 or overflow conversion. && (tree->gtOverflow() || varTypeIsLong(dstType)) #endif #endif // FEATURE_STACK_FP_X87 ) { oper = gtNewCastNode(TYP_DOUBLE, oper, TYP_DOUBLE); } // do we need to do it in two steps R -> I, '-> smallType #if defined(_TARGET_ARM64_) || defined(_TARGET_AMD64_) if (dstSize < genTypeSize(TYP_INT)) { oper = gtNewCastNodeL(TYP_INT, oper, TYP_INT); oper->gtFlags |= (tree->gtFlags & (GTF_UNSIGNED|GTF_OVERFLOW|GTF_EXCEPT)); tree->gtFlags &= ~GTF_UNSIGNED; } #else if (dstSize < sizeof(void*)) { oper = gtNewCastNodeL(TYP_I_IMPL, oper, TYP_I_IMPL); oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW|GTF_EXCEPT)); } #endif else { /* Note that if we need to use a helper call then we can not morph oper */ if (!tree->gtOverflow()) { #ifdef _TARGET_ARM64_ // On ARM64 All non-overflow checking conversions can be optimized goto OPTIMIZECAST; #else switch (dstType) { case TYP_INT: #ifdef _TARGET_X86_ // there is no rounding convert to integer instruction on ARM or x64 so skip this if ((oper->gtOper == GT_INTRINSIC) && (oper->gtIntrinsic.gtIntrinsicId == CORINFO_INTRINSIC_Round)) { /* optimization: conv.i4(round.d(d)) -> round.i(d) */ oper->gtType = dstType; return fgMorphTree(oper); } // if SSE2 is not enabled, we need the helper else if (!opts.compCanUseSSE2) { return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2INT, oper); } else #endif // _TARGET_X86_ { goto OPTIMIZECAST; } #if defined(_TARGET_ARM_) || defined(_TARGET_AMD64_) case TYP_UINT: goto OPTIMIZECAST; #else // _TARGET_ARM_ case TYP_UINT: return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2UINT, oper); #endif // _TARGET_ARM_ #ifdef _TARGET_AMD64_ // SSE2 has instructions to convert a float/double directly to a long case TYP_LONG: goto OPTIMIZECAST; #else case TYP_LONG: return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2LNG, oper); #endif //_TARGET_AMD64_ case TYP_ULONG: return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2ULNG, oper); default: break; } #endif // _TARGET_ARM64_ } else { switch (dstType) { case TYP_INT: return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2INT_OVF, oper); case TYP_UINT: return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2UINT_OVF, oper); case TYP_LONG: return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2LNG_OVF, oper); case TYP_ULONG: return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2ULNG_OVF, oper); default: break; } } noway_assert(!"Unexpected dstType"); } } #ifndef _TARGET_64BIT_ // The code generation phase (for x86 & ARM32) does not handle casts // directly from [u]long to anything other than [u]int. Insert an // intermediate cast to native int. else if (varTypeIsLong(srcType) && varTypeIsSmall(dstType)) { oper = gtNewCastNode(TYP_I_IMPL, oper, TYP_I_IMPL); oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW|GTF_EXCEPT|GTF_UNSIGNED)); tree->gtFlags &= ~GTF_UNSIGNED; } #endif //!_TARGET_64BIT_ #ifdef _TARGET_ARM_ else if ((dstType == TYP_FLOAT) && (srcType == TYP_DOUBLE) && (oper->gtOper == GT_CAST) && !varTypeIsLong(oper->gtCast.CastOp())) { // optimization: conv.r4(conv.r8(?)) -> conv.r4(d) // except when the ultimate source is a long because there is no long-to-float helper, so it must be 2 step. // This happens semi-frequently because there is no IL 'conv.r4.un' oper->gtType = TYP_FLOAT; oper->CastToType() = TYP_FLOAT; return fgMorphTree(oper); } // converts long/ulong --> float/double casts into helper calls. else if (varTypeIsFloating(dstType) && varTypeIsLong(srcType)) { if (dstType == TYP_FLOAT) { // there is only a double helper, so we // - change the dsttype to double // - insert a cast from double to float // - recurse into the resulting tree tree->CastToType() = TYP_DOUBLE; tree->gtType = TYP_DOUBLE; tree = gtNewCastNode(TYP_FLOAT, tree, TYP_FLOAT); return fgMorphTree(tree); } if (tree->gtFlags & GTF_UNSIGNED) return fgMorphCastIntoHelper(tree, CORINFO_HELP_ULNG2DBL, oper); return fgMorphCastIntoHelper(tree, CORINFO_HELP_LNG2DBL, oper); } #endif //_TARGET_ARM_ #ifdef _TARGET_AMD64_ // Do we have to do two step U4/8 -> R4/8 ? // Codegen supports the following conversion as one-step operation // a) Long -> R4/R8 // b) U8 -> R8 // // The following conversions are performed as two-step operations using above. // U4 -> R4/8 = U4-> Long -> R4/8 // U8 -> R4 = U8 -> R8 -> R4 else if ((tree->gtFlags & GTF_UNSIGNED) && varTypeIsFloating(dstType)) { srcType = genUnsignedType(srcType); if (srcType == TYP_ULONG) { if (dstType == TYP_FLOAT) { // Codegen can handle U8 -> R8 conversion. // U8 -> R4 = U8 -> R8 -> R4 // - change the dsttype to double // - insert a cast from double to float // - recurse into the resulting tree tree->CastToType() = TYP_DOUBLE; tree->gtType = TYP_DOUBLE; tree = gtNewCastNode(TYP_FLOAT, tree, TYP_FLOAT); return fgMorphTree(tree); } } else if (srcType == TYP_UINT) { oper = gtNewCastNode(TYP_LONG, oper, TYP_LONG); oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW|GTF_EXCEPT|GTF_UNSIGNED)); tree->gtFlags &= ~GTF_UNSIGNED; } } #endif // _TARGET_AMD64_ #ifdef _TARGET_X86_ // Do we have to do two step U4/8 -> R4/8 ? else if ((tree->gtFlags & GTF_UNSIGNED) && varTypeIsFloating(dstType)) { srcType = genUnsignedType(srcType); if (srcType == TYP_ULONG) { return fgMorphCastIntoHelper(tree, CORINFO_HELP_ULNG2DBL, oper); } else if (srcType == TYP_UINT) { oper = gtNewCastNode(TYP_LONG, oper, TYP_LONG); oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW|GTF_EXCEPT|GTF_UNSIGNED)); tree->gtFlags &= ~GTF_UNSIGNED; } } #endif //_TARGET_XARCH_ else if (varTypeIsGC(srcType) != varTypeIsGC(dstType)) { // We are casting away GC information. we would like to just // change the type to int, however this gives the emitter fits because // it believes the variable is a GC variable at the begining of the // instruction group, but is not turned non-gc by the code generator // we fix this by copying the GC pointer to a non-gc pointer temp. noway_assert(!varTypeIsGC(dstType) && "How can we have a cast to a GCRef here?"); // We generate an assignment to an int and then do the cast from an int. With this we avoid // the gc problem and we allow casts to bytes, longs, etc... unsigned lclNum = lvaGrabTemp(true DEBUGARG("Cast away GC")); oper->gtType = TYP_I_IMPL; GenTreePtr asg = gtNewTempAssign(lclNum, oper); oper->gtType = srcType; // do the real cast GenTreePtr cast = gtNewCastNode(tree->TypeGet(), gtNewLclvNode(lclNum, TYP_I_IMPL), dstType); // Generate the comma tree oper = gtNewOperNode(GT_COMMA, tree->TypeGet(), asg, cast); return fgMorphTree(oper); } // Look for narrowing casts ([u]long -> [u]int) and try to push them // down into the operand before morphing it. // // It doesn't matter if this is cast is from ulong or long (i.e. if // GTF_UNSIGNED is set) because the transformation is only applied to // overflow-insensitive narrowing casts, which always silently truncate. // // Note that casts from [u]long to small integer types are handled above. if ((srcType == TYP_LONG) && ((dstType == TYP_INT) || (dstType == TYP_UINT))) { // As a special case, look for overflow-sensitive casts of an AND // expression, and see if the second operand is a small constant. Since // the result of an AND is bound by its smaller operand, it may be // possible to prove that the cast won't overflow, which will in turn // allow the cast's operand to be transformed. if (tree->gtOverflow() && (oper->OperGet() == GT_AND)) { GenTreePtr andOp2 = oper->gtOp.gtOp2; // Special case to the special case: AND with a casted int. if ((andOp2->OperGet() == GT_CAST) && (andOp2->gtCast.CastOp()->OperGet() == GT_CNS_INT)) { // gtFoldExprConst will deal with whether the cast is signed or // unsigned, or overflow-sensitive. andOp2 = oper->gtOp.gtOp2 = gtFoldExprConst(andOp2); } // Look for a constant less than 2^{32} for a cast to uint, or less // than 2^{31} for a cast to int. int maxWidth = (dstType == TYP_UINT) ? 32 : 31; if ((andOp2->OperGet() == GT_CNS_NATIVELONG) && ((andOp2->gtIntConCommon.LngValue() >> maxWidth) == 0)) { // This cast can't overflow. tree->gtFlags &= ~(GTF_OVERFLOW | GTF_EXCEPT); } } // Only apply this transformation during global morph, // when neither the cast node nor the oper node may throw an exception // based on the upper 32 bits. // if (fgGlobalMorph && !tree->gtOverflow() && !oper->gtOverflowEx()) { // For these operations the lower 32 bits of the result only depends // upon the lower 32 bits of the operands // if ( (oper->OperGet() == GT_ADD) || (oper->OperGet() == GT_MUL) || (oper->OperGet() == GT_AND) || (oper->OperGet() == GT_OR) || (oper->OperGet() == GT_XOR) ) { DEBUG_DESTROY_NODE(tree); // Insert narrowing casts for op1 and op2 oper->gtOp.gtOp1 = gtNewCastNode(TYP_INT, oper->gtOp.gtOp1, dstType); oper->gtOp.gtOp2 = gtNewCastNode(TYP_INT, oper->gtOp.gtOp2, dstType); // Clear the GT_MUL_64RSLT if it is set if (oper->gtOper == GT_MUL && (oper->gtFlags & GTF_MUL_64RSLT)) oper->gtFlags &= ~GTF_MUL_64RSLT; // The operation now produces a 32-bit result. oper->gtType = TYP_INT; // Remorph the new tree as the casts that we added may be folded away. return fgMorphTree(oper); } } } OPTIMIZECAST: noway_assert(tree->gtOper == GT_CAST); /* Morph the operand */ tree->gtCast.CastOp() = oper = fgMorphTree(oper); /* Reset the call flag */ tree->gtFlags &= ~GTF_CALL; /* unless we have an overflow cast, reset the except flag */ if (!tree->gtOverflow()) tree->gtFlags &= ~GTF_EXCEPT; /* Just in case new side effects were introduced */ tree->gtFlags |= (oper->gtFlags & GTF_ALL_EFFECT); srcType = oper->TypeGet(); /* if GTF_UNSIGNED is set then force srcType to an unsigned type */ if (tree->gtFlags & GTF_UNSIGNED) srcType = genUnsignedType(srcType); srcSize = genTypeSize(srcType); if (!gtIsActiveCSE_Candidate(tree)) // tree cannot be a CSE candidate { /* See if we can discard the cast */ if (varTypeIsIntegral(srcType) && varTypeIsIntegral(dstType)) { if (srcType == dstType) // Certainly if they are identical it is pointless goto REMOVE_CAST; if (oper->OperGet() == GT_LCL_VAR && varTypeIsSmall(dstType)) { unsigned varNum = oper->gtLclVarCommon.gtLclNum; LclVarDsc * varDsc = &lvaTable[varNum]; if (varDsc->TypeGet() == dstType && varDsc->lvNormalizeOnStore()) goto REMOVE_CAST; } bool unsignedSrc = varTypeIsUnsigned(srcType); bool unsignedDst = varTypeIsUnsigned(dstType); bool signsDiffer = (unsignedSrc != unsignedDst); // For same sized casts with // the same signs or non-overflow cast we discard them as well if (srcSize == dstSize) { /* This should have been handled above */ noway_assert(varTypeIsGC(srcType) == varTypeIsGC(dstType)); if (!signsDiffer) goto REMOVE_CAST; if (!tree->gtOverflow()) { /* For small type casts, when necessary we force the src operand to the dstType and allow the implied load from memory to perform the casting */ if (varTypeIsSmall(srcType)) { switch (oper->gtOper) { case GT_IND: case GT_CLS_VAR: case GT_LCL_FLD: case GT_ARR_ELEM: oper->gtType = dstType; goto REMOVE_CAST; default: break; } } else goto REMOVE_CAST; } } if (srcSize < dstSize) // widening cast { // Keep any long casts if (dstSize == sizeof(int)) { // Only keep signed to unsigned widening cast with overflow check if (!tree->gtOverflow() || !unsignedDst || unsignedSrc) goto REMOVE_CAST; } // Casts from signed->unsigned can never overflow while widening if (unsignedSrc || !unsignedDst) tree->gtFlags &= ~GTF_OVERFLOW; } else { // Try to narrow the operand of the cast and discard the cast // Note: Do not narrow a cast that is marked as a CSE // And do not narrow if the oper is marked as a CSE either // if (!tree->gtOverflow() && !gtIsActiveCSE_Candidate(oper) && (opts.compFlags & CLFLG_TREETRANS) && optNarrowTree(oper, srcType, dstType, tree->gtVNPair, false)) { optNarrowTree(oper, srcType, dstType, tree->gtVNPair, true); /* If oper is changed into a cast to TYP_INT, or to a GT_NOP, we may need to discard it */ if (oper->gtOper == GT_CAST && oper->CastToType() == genActualType(oper->CastFromType())) { oper = oper->gtCast.CastOp(); } goto REMOVE_CAST; } } } switch (oper->gtOper) { /* If the operand is a constant, we'll fold it */ case GT_CNS_INT: case GT_CNS_LNG: case GT_CNS_DBL: case GT_CNS_STR: { GenTreePtr oldTree = tree; tree = gtFoldExprConst(tree); // This may not fold the constant (NaN ...) // Did we get a comma throw as a result of gtFoldExprConst? if ((oldTree != tree) && (oldTree->gtOper != GT_COMMA)) { noway_assert(fgIsCommaThrow(tree)); tree->gtOp.gtOp1 = fgMorphTree(tree->gtOp.gtOp1); fgMorphTreeDone(tree); return tree; } else if (tree->gtOper != GT_CAST) return tree; noway_assert(tree->gtCast.CastOp() == oper); // unchanged } break; case GT_CAST: /* Check for two consecutive casts into the same dstType */ if (!tree->gtOverflow()) { var_types dstType2 = oper->CastToType(); if (dstType == dstType2) goto REMOVE_CAST; } break; /* If op1 is a mod node, mark it with the GTF_MOD_INT_RESULT flag so that the code generator will know not to convert the result of the idiv to a regpair */ case GT_MOD: if (dstType == TYP_INT) tree->gtOp.gtOp1->gtFlags |= GTF_MOD_INT_RESULT; break; case GT_UMOD: if (dstType == TYP_UINT) tree->gtOp.gtOp1->gtFlags |= GTF_MOD_INT_RESULT; break; case GT_COMMA: // Check for cast of a GT_COMMA with a throw overflow // Bug 110829: Since this optimization will bash the types // neither oper or commaOp2 can be CSE candidates if (fgIsCommaThrow(oper) && !gtIsActiveCSE_Candidate(oper)) // oper can not be a CSE candidate { GenTreePtr commaOp2 = oper->gtOp.gtOp2; if (!gtIsActiveCSE_Candidate(commaOp2)) // commaOp2 can not be a CSE candidate { // need type of oper to be same as tree if (tree->gtType == TYP_LONG) { commaOp2->ChangeOperConst(GT_CNS_NATIVELONG); commaOp2->gtIntConCommon.SetLngValue(0); /* Change the types of oper and commaOp2 to TYP_LONG */ oper->gtType = commaOp2->gtType = TYP_LONG; } else if (varTypeIsFloating(tree->gtType)) { commaOp2->ChangeOperConst(GT_CNS_DBL); commaOp2->gtDblCon.gtDconVal = 0.0; // Change the types of oper and commaOp2 // X87 promotes everything to TYP_DOUBLE // But other's are a little more precise const var_types newTyp #if FEATURE_X87_DOUBLES = TYP_DOUBLE; #else // FEATURE_X87_DOUBLES = tree->gtType; #endif // FEATURE_X87_DOUBLES oper->gtType = commaOp2->gtType = newTyp; } else { commaOp2->ChangeOperConst(GT_CNS_INT); commaOp2->gtIntCon.gtIconVal = 0; /* Change the types of oper and commaOp2 to TYP_INT */ oper->gtType = commaOp2->gtType = TYP_INT; } } if (vnStore != nullptr) { fgValueNumberTreeConst(commaOp2); } /* Return the GT_COMMA node as the new tree */ return oper; } break; default: break; } /* end switch (oper->gtOper) */ } if (tree->gtOverflow()) fgAddCodeRef(compCurBB, bbThrowIndex(compCurBB), SCK_OVERFLOW, fgPtrArgCntCur); return tree; REMOVE_CAST: /* Here we've eliminated the cast, so just return it's operand */ assert(!gtIsActiveCSE_Candidate(tree)); // tree cannot be a CSE candidate DEBUG_DESTROY_NODE(tree); return oper; } #ifdef _PREFAST_ #pragma warning(pop) #endif /***************************************************************************** * * Perform an unwrap operation on a Proxy object */ GenTreePtr Compiler::fgUnwrapProxy(GenTreePtr objRef) { assert(info.compIsContextful && info.compUnwrapContextful && impIsThis(objRef)); CORINFO_EE_INFO * pInfo = eeGetEEInfo(); GenTreePtr addTree; // Perform the unwrap: // // This requires two extra indirections. // We mark these indirections as 'invariant' and // the CSE logic will hoist them when appropriate. // // Note that each dereference is a GC pointer addTree = gtNewOperNode(GT_ADD, TYP_I_IMPL, objRef, gtNewIconNode(pInfo->offsetOfTransparentProxyRP, TYP_I_IMPL)); objRef = gtNewOperNode(GT_IND, TYP_REF, addTree); objRef->gtFlags |= GTF_IND_INVARIANT; addTree = gtNewOperNode(GT_ADD, TYP_I_IMPL, objRef, gtNewIconNode(pInfo->offsetOfRealProxyServer, TYP_I_IMPL)); objRef = gtNewOperNode(GT_IND, TYP_REF, addTree); objRef->gtFlags |= GTF_IND_INVARIANT; // objRef now hold the 'real this' reference (i.e. the unwrapped proxy) return objRef; } /***************************************************************************** * * Morph an argument list; compute the pointer argument count in the process. * * NOTE: This function can be called from any place in the JIT to perform re-morphing * due to graph altering modifications such as copy / constant propagation */ unsigned UpdateGT_LISTFlags(GenTreePtr tree) { assert(tree->gtOper == GT_LIST); unsigned flags = 0; if (tree->gtOp.gtOp2) { flags |= UpdateGT_LISTFlags(tree->gtOp.gtOp2); } flags |= (tree->gtOp.gtOp1->gtFlags & GTF_ALL_EFFECT); tree->gtFlags &= ~GTF_ALL_EFFECT; tree->gtFlags |= flags; return tree->gtFlags; } fgArgInfo::fgArgInfo(Compiler * comp, GenTreePtr call, unsigned numArgs) { compiler = comp; callTree = call; assert(call->IsCall()); argCount = 0; // filled in arg count, starts at zero nextSlotNum = INIT_ARG_STACK_SLOT; stkLevel = 0; argTableSize = numArgs; // the allocated table size argsComplete = false; argsSorted = false; if (argTableSize == 0) argTable = NULL; else argTable = new(compiler, CMK_fgArgInfoPtrArr) fgArgTabEntryPtr[argTableSize]; } /***************************************************************************** * * fgArgInfo Copy Constructor * * This method needs to act like a copy constructor for fgArgInfo. * The newCall needs to have its fgArgInfo initialized such that * we have newCall that is an exact copy of the oldCall. * We have to take care since the argument information * in the argTable contains pointers that must point to the * new arguments and not the old arguments. */ fgArgInfo::fgArgInfo(GenTreePtr newCall, GenTreePtr oldCall) { assert(oldCall->IsCall()); assert(newCall->IsCall()); fgArgInfoPtr oldArgInfo = oldCall->gtCall.fgArgInfo; compiler = oldArgInfo->compiler;; callTree = newCall; assert(newCall->IsCall()); argCount = 0; // filled in arg count, starts at zero nextSlotNum = INIT_ARG_STACK_SLOT; stkLevel = oldArgInfo->stkLevel; argTableSize = oldArgInfo->argTableSize; argsComplete = false; argTable = NULL; if (argTableSize > 0) { argTable = new(compiler, CMK_fgArgInfoPtrArr) fgArgTabEntryPtr[argTableSize]; for (unsigned inx=0; inx<argTableSize; inx++) { argTable[inx] = NULL; } } assert(oldArgInfo->argsComplete); // We create local, artificial GenTreeArgLists that includes the gtCallObjp, if that exists, as first argument, // so we can iterate over these argument lists more uniformly. // Need to provide a temporary non-null first arguments to these constructors: if we use them, we'll replace them GenTreeArgList* newArgs; GenTreeArgList newArgObjp(newCall, newCall->gtCall.gtCallArgs); GenTreeArgList* oldArgs; GenTreeArgList oldArgObjp(oldCall, oldCall->gtCall.gtCallArgs); if (newCall->gtCall.gtCallObjp == NULL) { assert(oldCall->gtCall.gtCallObjp == NULL); newArgs = newCall->gtCall.gtCallArgs; oldArgs = oldCall->gtCall.gtCallArgs; } else { assert(oldCall->gtCall.gtCallObjp != NULL); newArgObjp.Current() = newCall->gtCall.gtCallArgs; newArgs = &newArgObjp; oldArgObjp.Current() = oldCall->gtCall.gtCallObjp; oldArgs = &oldArgObjp; } GenTreePtr newCurr; GenTreePtr oldCurr; GenTreeArgList* newParent = NULL; GenTreeArgList* oldParent = NULL; fgArgTabEntryPtr * oldArgTable = oldArgInfo->argTable; bool scanRegArgs = false; while (newArgs) { /* Get hold of the next argument values for the oldCall and newCall */ newCurr = newArgs->Current(); oldCurr = oldArgs->Current(); if (newArgs != &newArgObjp) { newParent = newArgs; oldParent = oldArgs; } else { assert(newParent == NULL && oldParent == NULL); } newArgs = newArgs->Rest(); oldArgs = oldArgs->Rest(); fgArgTabEntryPtr oldArgTabEntry = NULL; fgArgTabEntryPtr newArgTabEntry = NULL; for (unsigned inx=0; inx<argTableSize; inx++) { oldArgTabEntry = oldArgTable[inx]; if (oldArgTabEntry->parent == oldParent) { assert((oldParent == NULL) == (newParent == NULL)); // We have found the matching "parent" field in oldArgTabEntry newArgTabEntry = new (compiler, CMK_fgArgInfo) fgArgTabEntry; // First block copy all fields // *newArgTabEntry = *oldArgTabEntry; // Then update all GenTreePtr fields in the newArgTabEntry // newArgTabEntry->parent = newParent; // The node field is likely to have been updated // to point at a node in the gtCallLateArgs list // if (oldArgTabEntry->node == oldCurr) { // node is not pointing into the gtCallLateArgs list newArgTabEntry->node = newCurr; } else { // node must be pointing into the gtCallLateArgs list // // We will fix this pointer up in the next loop // newArgTabEntry->node = NULL; // For now we assign a NULL to this field scanRegArgs = true; } // Now initialize the proper element in the argTable array // argTable[inx] = newArgTabEntry; break; } } // We should have found the matching oldArgTabEntry and created the newArgTabEntry // assert(newArgTabEntry != NULL); } if (scanRegArgs) { newArgs = newCall->gtCall.gtCallLateArgs; oldArgs = oldCall->gtCall.gtCallLateArgs; while (newArgs) { /* Get hold of the next argument values for the oldCall and newCall */ assert(newArgs->IsList()); newCurr = newArgs->Current(); newArgs = newArgs->Rest(); assert(oldArgs->IsList()); oldCurr = oldArgs->Current(); oldArgs = oldArgs->Rest(); fgArgTabEntryPtr oldArgTabEntry = NULL; fgArgTabEntryPtr newArgTabEntry = NULL; for (unsigned inx=0; inx<argTableSize; inx++) { oldArgTabEntry = oldArgTable[inx]; if (oldArgTabEntry->node == oldCurr) { // We have found the matching "node" field in oldArgTabEntry newArgTabEntry = argTable[inx]; assert(newArgTabEntry != NULL); // update the "node" GenTreePtr fields in the newArgTabEntry // assert(newArgTabEntry->node == NULL); // We previously assigned NULL to this field newArgTabEntry->node = newCurr; break; } } } } argCount = oldArgInfo->argCount; nextSlotNum = oldArgInfo->nextSlotNum; argsComplete = true; argsSorted = true; } void fgArgInfo::AddArg(fgArgTabEntryPtr curArgTabEntry) { assert(argCount < argTableSize); argTable[argCount] = curArgTabEntry; argCount++; } fgArgTabEntryPtr fgArgInfo::AddRegArg(unsigned argNum, GenTreePtr node, GenTreePtr parent, regNumber regNum, unsigned numRegs, unsigned alignment) { fgArgTabEntryPtr curArgTabEntry = new(compiler, CMK_fgArgInfo) fgArgTabEntry; curArgTabEntry->argNum = argNum; curArgTabEntry->node = node; curArgTabEntry->parent = parent; curArgTabEntry->regNum = regNum; curArgTabEntry->slotNum = 0; curArgTabEntry->numRegs = numRegs; curArgTabEntry->numSlots = 0; curArgTabEntry->alignment = alignment; curArgTabEntry->lateArgInx = (unsigned)-1; curArgTabEntry->tmpNum = (unsigned)-1; curArgTabEntry->isSplit = false; curArgTabEntry->isTmp = false; curArgTabEntry->needTmp = false; curArgTabEntry->needPlace = false; curArgTabEntry->processed = false; curArgTabEntry->isHfaRegArg = false; curArgTabEntry->isBackFilled = false; curArgTabEntry->isNonStandard = false; AddArg(curArgTabEntry); return curArgTabEntry; } #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) fgArgTabEntryPtr fgArgInfo::AddRegArg(unsigned argNum, GenTreePtr node, GenTreePtr parent, regNumber regNum, unsigned numRegs, unsigned alignment, const bool isStruct, const regNumber otherRegNum, const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* const structDescPtr) { fgArgTabEntryPtr curArgTabEntry = AddRegArg(argNum, node, parent, regNum, numRegs, alignment); assert(curArgTabEntry != nullptr); // The node of the ArgTabEntry could change after remorphing - it could be rewritten to a cpyblk or a // PlaceHolder node (in case of needed late argument, for example.) // This requires using of an extra flag. At creation time the state is right, so // and this assert enforces that. assert((varTypeIsStruct(node) && isStruct) || (!varTypeIsStruct(node) && !isStruct)); curArgTabEntry->otherRegNum = otherRegNum; // Second reg for the struct curArgTabEntry->isStruct = isStruct; // is this a struct arg if (isStruct && structDescPtr != nullptr) { curArgTabEntry->structDesc.CopyFrom(*structDescPtr); } return curArgTabEntry; } #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) fgArgTabEntryPtr fgArgInfo::AddStkArg(unsigned argNum, GenTreePtr node, GenTreePtr parent, unsigned numSlots, unsigned alignment FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(const bool isStruct)) { fgArgTabEntryPtr curArgTabEntry = new(compiler, CMK_fgArgInfo) fgArgTabEntry; nextSlotNum = (unsigned)roundUp(nextSlotNum, alignment); #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) // The node of the ArgTabEntry could change after remorphing - it could be rewritten to a cpyblk or a // PlaceHolder node (in case of needed late argument, for example.) // This reqires using of an extra flag. At creation time the state is right, so // and this assert enforces that. assert((varTypeIsStruct(node) && isStruct) || (!varTypeIsStruct(node) && !isStruct)); curArgTabEntry->isStruct = isStruct; // is this a struct arg #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) curArgTabEntry->argNum = argNum; curArgTabEntry->node = node; curArgTabEntry->parent = parent; curArgTabEntry->regNum = REG_STK; curArgTabEntry->slotNum = nextSlotNum; curArgTabEntry->numRegs = 0; curArgTabEntry->numSlots = numSlots; curArgTabEntry->alignment = alignment; curArgTabEntry->lateArgInx = (unsigned) -1; curArgTabEntry->tmpNum = (unsigned) -1; curArgTabEntry->isSplit = false; curArgTabEntry->isTmp = false; curArgTabEntry->needTmp = false; curArgTabEntry->needPlace = false; curArgTabEntry->processed = false; curArgTabEntry->isHfaRegArg = false; curArgTabEntry->isBackFilled = false; curArgTabEntry->isNonStandard = false; AddArg(curArgTabEntry); nextSlotNum += numSlots; return curArgTabEntry; } void fgArgInfo::RemorphReset() { nextSlotNum = INIT_ARG_STACK_SLOT; } fgArgTabEntry* fgArgInfo::RemorphRegArg(unsigned argNum, GenTreePtr node, GenTreePtr parent, regNumber regNum, unsigned numRegs, unsigned alignment) { fgArgTabEntryPtr curArgTabEntry = NULL; unsigned regArgInx = 0; unsigned inx; for (inx=0; inx < argCount; inx++) { curArgTabEntry = argTable[inx]; if (curArgTabEntry->argNum == argNum) break; bool isRegArg; GenTreePtr argx; if (curArgTabEntry->parent != NULL) { assert(curArgTabEntry->parent->IsList()); argx = curArgTabEntry->parent->Current(); isRegArg = (argx->gtFlags & GTF_LATE_ARG) != 0; } else { argx = curArgTabEntry->node; isRegArg = true; } if (isRegArg) { regArgInx++; } } // if this was a nonstandard arg the table is definitive if (curArgTabEntry->isNonStandard) regNum = curArgTabEntry->regNum; assert(curArgTabEntry->argNum == argNum); assert(curArgTabEntry->regNum == regNum); assert(curArgTabEntry->alignment == alignment); assert(curArgTabEntry->parent == parent); if (curArgTabEntry->node != node) { GenTreePtr argx = NULL; unsigned regIndex = 0; /* process the register argument list */ for (GenTreeArgList* list = callTree->gtCall.gtCallLateArgs; list; (regIndex++, list = list->Rest())) { argx = list->Current(); assert(!argx->IsArgPlaceHolderNode()); // No place holders nodes are in gtCallLateArgs; if (regIndex == regArgInx) break; } assert(regIndex == regArgInx); assert(regArgInx == curArgTabEntry->lateArgInx); if (curArgTabEntry->node != argx) { curArgTabEntry->node = argx; } } return curArgTabEntry; } void fgArgInfo::RemorphStkArg(unsigned argNum, GenTreePtr node, GenTreePtr parent, unsigned numSlots, unsigned alignment) { fgArgTabEntryPtr curArgTabEntry = NULL; bool isRegArg = false; unsigned regArgInx = 0; GenTreePtr argx; unsigned inx; for (inx=0; inx < argCount; inx++) { curArgTabEntry = argTable[inx]; if (curArgTabEntry->parent != NULL) { assert(curArgTabEntry->parent->IsList()); argx = curArgTabEntry->parent->Current(); isRegArg = (argx->gtFlags & GTF_LATE_ARG) != 0; } else { argx = curArgTabEntry->node; isRegArg = true; } if (curArgTabEntry->argNum == argNum) break; if (isRegArg) regArgInx++; } nextSlotNum = (unsigned) roundUp(nextSlotNum, alignment); assert(curArgTabEntry->argNum == argNum); assert(curArgTabEntry->slotNum == nextSlotNum); assert(curArgTabEntry->numSlots == numSlots); assert(curArgTabEntry->alignment == alignment); assert(curArgTabEntry->parent == parent); assert(parent->IsList()); #if FEATURE_FIXED_OUT_ARGS if (curArgTabEntry->node != node) { if (isRegArg) { GenTreePtr argx = NULL; unsigned regIndex = 0; /* process the register argument list */ for (GenTreeArgList * list = callTree->gtCall.gtCallLateArgs; list; list = list->Rest(), regIndex++) { argx = list->Current(); assert(!argx->IsArgPlaceHolderNode()); // No place holders nodes are in gtCallLateArgs; if (regIndex == regArgInx) break; } assert(regIndex == regArgInx); assert(regArgInx == curArgTabEntry->lateArgInx); if (curArgTabEntry->node != argx) { curArgTabEntry->node = argx; } } else { assert(parent->Current() == node); curArgTabEntry->node = node; } } #else curArgTabEntry->node = node; #endif nextSlotNum += numSlots; } void fgArgInfo::SplitArg(unsigned argNum, unsigned numRegs, unsigned numSlots) { fgArgTabEntryPtr curArgTabEntry = NULL; assert(argNum < argCount); for (unsigned inx=0; inx < argCount; inx++) { curArgTabEntry = argTable[inx]; if (curArgTabEntry->argNum == argNum) break; } assert(numRegs > 0); assert(numSlots > 0); curArgTabEntry->isSplit = true; curArgTabEntry->numRegs = numRegs; curArgTabEntry->numSlots = numSlots; nextSlotNum += numSlots; } void fgArgInfo::EvalToTmp(unsigned argNum, unsigned tmpNum, GenTreePtr newNode) { fgArgTabEntryPtr curArgTabEntry = NULL; assert(argNum < argCount); for (unsigned inx=0; inx < argCount; inx++) { curArgTabEntry = argTable[inx]; if (curArgTabEntry->argNum == argNum) break; } assert(curArgTabEntry->parent->Current() == newNode); curArgTabEntry->node = newNode; curArgTabEntry->tmpNum = tmpNum; curArgTabEntry->isTmp = true; } void fgArgInfo::ArgsComplete() { bool hasStackArgs = false; bool hasStructRegArg = false; for (unsigned curInx = 0; curInx < argCount; curInx++) { fgArgTabEntryPtr curArgTabEntry = argTable[curInx]; assert(curArgTabEntry != NULL); GenTreePtr argx = curArgTabEntry->node; #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) // If this is a struct, mark it for needing a tempVar. // In the copyblk and store this should have minimal perf impact since // the local vars where we copy/store to already exist and the logic for temp // var will not create a new one if it creates a tempVar from another tempVar. // (Debugging through the code, there was no new copy of data created, neither a new tempVar.) // The need for this arise from Lower::LowerArg. // In case of copyblk and store operation, the NewPutArg method will // not be invoked and the struct will not be loaded to be passed in // registers or by value on the stack. if (varTypeIsStruct(argx) FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY( || curArgTabEntry->isStruct)) { curArgTabEntry->needTmp = true; } #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) if (curArgTabEntry->regNum == REG_STK) { hasStackArgs = true; #if !FEATURE_FIXED_OUT_ARGS // On x86 we use push instructions to pass arguments: // The non-register arguments are evaluated and pushed in order // and they are never evaluated into temps // continue; #endif } else // we have a register argument, next we look for a struct type. { if (varTypeIsStruct(argx) FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY( || curArgTabEntry->isStruct)) { hasStructRegArg = true; } } /* If the argument tree contains an assignment (GTF_ASG) then the argument and and every earlier argument (except constants) must be evaluated into temps since there may be other arguments that follow and they may use the value being assigned. EXAMPLE: ArgTab is "a, a=5, a" -> when we see the second arg "a=5" we know the first two arguments "a, a=5" have to be evaluated into temps For the case of an assignment, we only know that there exist some assignment someplace in the tree. We don't know what is being assigned so we are very conservative here and assume that any local variable could have been assigned. */ if (argx->gtFlags & GTF_ASG) { // If this is not the only argument, or it's a copyblk, or it already evaluates the expression to // a tmp, then we need a temp in the late arg list. if ((argCount > 1) || argx->OperIsCopyBlkOp() #ifdef FEATURE_FIXED_OUT_ARGS || curArgTabEntry->isTmp // I protect this by "FEATURE_FIXED_OUT_ARGS" to preserve the property // that we only have late non-register args when that feature is on. #endif // FEATURE_FIXED_OUT_ARGS ) { curArgTabEntry->needTmp = true; } // For all previous arguments, unless they are a simple constant // we require that they be evaluated into temps for (unsigned prevInx = 0; prevInx < curInx; prevInx++) { fgArgTabEntryPtr prevArgTabEntry = argTable[prevInx]; assert(prevArgTabEntry->argNum < curArgTabEntry->argNum); assert(prevArgTabEntry->node); if (prevArgTabEntry->node->gtOper != GT_CNS_INT) { prevArgTabEntry->needTmp = true; } } } #if FEATURE_FIXED_OUT_ARGS // Like calls, if this argument has a tree that will do an inline throw, // a call to a jit helper, then we need to treat it like a call (but only // if there are/were any stack args). // This means unnesting, sorting, etc. Technically this is overly // conservative, but I want to avoid as much special-case debug-only code // as possible, so leveraging the GTF_CALL flag is the easiest. if (!(argx->gtFlags & GTF_CALL) && (argx->gtFlags & GTF_EXCEPT) && (argCount > 1) && compiler->opts.compDbgCode && (compiler->fgWalkTreePre(&argx, Compiler::fgChkThrowCB) == Compiler::WALK_ABORT)) { for (unsigned otherInx = 0; otherInx < argCount; otherInx++) { if (otherInx == curInx) continue; if (argTable[otherInx]->regNum == REG_STK) { argx->gtFlags |= GTF_CALL; break; } } } #endif // FEATURE_FIXED_OUT_ARGS /* If it contains a call (GTF_CALL) then itself and everything before the call with a GLOB_EFFECT must eval to temp (this is because everything with SIDE_EFFECT has to be kept in the right order since we will move the call to the first position) For calls we don't have to be quite as conservative as we are with an assignment since the call won't be modifying any non-address taken LclVars. */ if (argx->gtFlags & GTF_CALL) { if (argCount > 1) // If this is not the only argument { curArgTabEntry->needTmp = true; } else if (varTypeIsFloating(argx->TypeGet()) && (argx->OperGet() == GT_CALL)) { // Spill all arguments that are floating point calls curArgTabEntry->needTmp = true; } // All previous arguments may need to be evaluated into temps for (unsigned prevInx = 0; prevInx < curInx; prevInx++) { fgArgTabEntryPtr prevArgTabEntry = argTable[prevInx]; assert(prevArgTabEntry->argNum < curArgTabEntry->argNum); assert(prevArgTabEntry->node); // For all previous arguments, if they have any GTF_ALL_EFFECT // we require that they be evaluated into a temp if ((prevArgTabEntry->node->gtFlags & GTF_ALL_EFFECT) != 0) { prevArgTabEntry->needTmp = true; } #if FEATURE_FIXED_OUT_ARGS // Or, if they are stored into the FIXED_OUT_ARG area // we require that they be moved to the gtCallLateArgs // and replaced with a placeholder node else if (prevArgTabEntry->regNum == REG_STK) { prevArgTabEntry->needPlace = true; } #endif } } } // We only care because we can't spill structs and qmarks involve a lot of spilling, but // if we don't have qmarks, then it doesn't matter. // So check for Qmark's globally once here, instead of inside the loop. // const bool hasStructRegArgWeCareAbout = (hasStructRegArg && compiler->compQmarkUsed); #if FEATURE_FIXED_OUT_ARGS // For Arm/x64 we only care because we can't reorder a register // argument that uses GT_LCLHEAP. This is an optimization to // save a check inside the below loop. // const bool hasStackArgsWeCareAbout = (hasStackArgs && compiler->compLocallocUsed); #else const bool hasStackArgsWeCareAbout = hasStackArgs; #endif // FEATURE_FIXED_OUT_ARGS // If we have any stack args we have to force the evaluation // of any arguments passed in registers that might throw an exception // // Technically we only a required to handle the following two cases: // a GT_IND with GTF_IND_RNGCHK (only on x86) or // a GT_LCLHEAP node that allocates stuff on the stack // if (hasStackArgsWeCareAbout || hasStructRegArgWeCareAbout) { for (unsigned curInx = 0; curInx < argCount; curInx++) { fgArgTabEntryPtr curArgTabEntry = argTable[curInx]; assert(curArgTabEntry != NULL); GenTreePtr argx = curArgTabEntry->node; // Examine the register args that are currently not marked needTmp // if (!curArgTabEntry->needTmp && (curArgTabEntry->regNum != REG_STK)) { if (hasStackArgsWeCareAbout) { #if !FEATURE_FIXED_OUT_ARGS // On x86 we previously recorded a stack depth of zero when // morphing the register arguments of any GT_IND with a GTF_IND_RNGCHK flag // Thus we can not reorder the argument after any stack based argument // (Note that GT_LCLHEAP sets the GTF_EXCEPT flag so we don't need to // check for it explicitly // if (argx->gtFlags & GTF_EXCEPT) { curArgTabEntry->needTmp = true; continue; } #else // For Arm/X64 we can't reorder a register argument that uses a GT_LCLHEAP // if (argx->gtFlags & GTF_EXCEPT) { assert(compiler->compLocallocUsed); // Returns WALK_ABORT if a GT_LCLHEAP node is encountered in the argx tree // if (compiler->fgWalkTreePre(&argx, Compiler::fgChkLocAllocCB) == Compiler::WALK_ABORT) { curArgTabEntry->needTmp = true; continue; } } #endif } if (hasStructRegArgWeCareAbout) { // Returns true if a GT_QMARK node is encountered in the argx tree // if (compiler->fgWalkTreePre(&argx, Compiler::fgChkQmarkCB) == Compiler::WALK_ABORT) { curArgTabEntry->needTmp = true; continue; } } } } } argsComplete = true; } void fgArgInfo::SortArgs() { assert(argsComplete == true); /* Shuffle the arguments around before we build the gtCallLateArgs list. The idea is to move all "simple" arguments like constants and local vars to the end of the table, and move the complex arguments towards the beginning of the table. This will help prevent registers from being spilled by allowing us to evaluate the more complex arguments before the simpler arguments. The argTable ends up looking like: +------------------------------------+ <--- argTable[argCount - 1] | constants | +------------------------------------+ | local var / local field | +------------------------------------+ | remaining arguments sorted by cost | +------------------------------------+ | temps (argTable[].needTmp = true) | +------------------------------------+ | args with calls (GTF_CALL) | +------------------------------------+ <--- argTable[0] */ #ifdef DEBUG if (compiler->verbose) { printf("\nSorting the arguments:\n"); } #endif /* Set the beginning and end for the new argument table */ unsigned curInx; int regCount = 0; unsigned begTab = 0; unsigned endTab = argCount - 1; unsigned argsRemaining = argCount; // First take care of arguments that are constants. // [We use a backward iterator pattern] // curInx = argCount; do { curInx--; fgArgTabEntryPtr curArgTabEntry = argTable[curInx]; if (curArgTabEntry->regNum != REG_STK) regCount++; // Skip any already processed args // if (!curArgTabEntry->processed) { GenTreePtr argx = curArgTabEntry->node; // put constants at the end of the table // if (argx->gtOper == GT_CNS_INT) { noway_assert(curInx <= endTab); curArgTabEntry->processed = true; // place curArgTabEntry at the endTab position by performing a swap // if (curInx != endTab) { argTable[curInx] = argTable[endTab]; argTable[endTab] = curArgTabEntry; } endTab--; argsRemaining--; } } } while (curInx > 0); if (argsRemaining > 0) { // Next take care of arguments that are calls. // [We use a forward iterator pattern] // for (curInx = begTab; curInx <= endTab; curInx++) { fgArgTabEntryPtr curArgTabEntry = argTable[curInx]; // Skip any already processed args // if (!curArgTabEntry->processed) { GenTreePtr argx = curArgTabEntry->node; // put calls at the beginning of the table // if (argx->gtFlags & GTF_CALL) { curArgTabEntry->processed = true; // place curArgTabEntry at the begTab position by performing a swap // if (curInx != begTab) { argTable[curInx] = argTable[begTab]; argTable[begTab] = curArgTabEntry; } begTab++; argsRemaining--; } } } } if (argsRemaining > 0) { // Next take care arguments that are temps. // These temps come before the arguments that are // ordinary local vars or local fields // since this will give them a better chance to become // enregistered into their actual argument register. // [We use a forward iterator pattern] // for (curInx = begTab; curInx <= endTab; curInx++) { fgArgTabEntryPtr curArgTabEntry = argTable[curInx]; // Skip any already processed args // if (!curArgTabEntry->processed) { if (curArgTabEntry->needTmp) { curArgTabEntry->processed = true; // place curArgTabEntry at the begTab position by performing a swap // if (curInx != begTab) { argTable[curInx] = argTable[begTab]; argTable[begTab] = curArgTabEntry; } begTab++; argsRemaining--; } } } } if (argsRemaining > 0) { // Next take care of local var and local field arguments. // These are moved towards the end of the argument evaluation. // [We use a backward iterator pattern] // curInx = endTab + 1; do { curInx--; fgArgTabEntryPtr curArgTabEntry = argTable[curInx]; // Skip any already processed args // if (!curArgTabEntry->processed) { GenTreePtr argx = curArgTabEntry->node; if ((argx->gtOper == GT_LCL_VAR) || (argx->gtOper == GT_LCL_FLD)) { noway_assert(curInx <= endTab); curArgTabEntry->processed = true; // place curArgTabEntry at the endTab position by performing a swap // if (curInx != endTab) { argTable[curInx] = argTable[endTab]; argTable[endTab] = curArgTabEntry; } endTab--; argsRemaining--; } } } while (curInx > begTab); } // Finally, take care of all the remaining arguments. // Note that we fill in one arg at a time using a while loop. bool costsPrepared = false; // Only prepare tree costs once, the first time through this loop while (argsRemaining > 0) { /* Find the most expensive arg remaining and evaluate it next */ fgArgTabEntryPtr expensiveArgTabEntry = NULL; unsigned expensiveArg = UINT_MAX; unsigned expensiveArgCost = 0; // [We use a forward iterator pattern] // for (curInx = begTab; curInx <= endTab; curInx++) { fgArgTabEntryPtr curArgTabEntry = argTable[curInx]; // Skip any already processed args // if (!curArgTabEntry->processed) { GenTreePtr argx = curArgTabEntry->node; // We should have already handled these kinds of args assert (argx->gtOper != GT_LCL_VAR); assert (argx->gtOper != GT_LCL_FLD); assert (argx->gtOper != GT_CNS_INT); // This arg should either have no persistent side effects or be the last one in our table // assert(((argx->gtFlags & GTF_PERSISTENT_SIDE_EFFECTS) == 0) || (curInx == (argCount-1))); if (argsRemaining == 1) { // This is the last arg to place expensiveArg = curInx; expensiveArgTabEntry = curArgTabEntry; assert(begTab == endTab); break; } else { if (!costsPrepared) { /* We call gtPrepareCost to measure the cost of evaluating this tree */ compiler->gtPrepareCost(argx); } if (argx->gtCostEx > expensiveArgCost) { // Remember this arg as the most expensive one that we have yet seen expensiveArgCost = argx->gtCostEx; expensiveArg = curInx; expensiveArgTabEntry = curArgTabEntry; } } } } noway_assert(expensiveArg != UINT_MAX); // put the most expensive arg towards the beginning of the table expensiveArgTabEntry->processed = true; // place expensiveArgTabEntry at the begTab position by performing a swap // if (expensiveArg != begTab) { argTable[expensiveArg] = argTable[begTab]; argTable[begTab] = expensiveArgTabEntry; } begTab++; argsRemaining--; costsPrepared = true; // If we have more expensive arguments, don't re-evaluate the tree cost on the next loop } // The table should now be completely filled and thus begTab should now be adjacent to endTab // and regArgsRemaining should be zero assert(begTab == (endTab + 1)); assert(argsRemaining == 0); #if !FEATURE_FIXED_OUT_ARGS // Finally build the regArgList // callTree->gtCall.regArgList = NULL; callTree->gtCall.regArgListCount = regCount; unsigned regInx = 0; for (curInx = 0; curInx < argCount; curInx++) { fgArgTabEntryPtr curArgTabEntry = argTable[curInx]; if (curArgTabEntry->regNum != REG_STK) { // Encode the argument register in the register mask // callTree->gtCall.regArgList[regInx] = curArgTabEntry->regNum; regInx++; } } #endif // !FEATURE_FIXED_OUT_ARGS argsSorted = true; } //------------------------------------------------------------------------------ // fgMakeTmpArgNode : This function creates a tmp var only if needed. // We need this to be done in order to enforce ordering // of the evaluation of arguments. // // Arguments: // tmpVarNum - the var num which we clone into the newly created temp var. // // Return Value: // the newly created temp var tree. GenTreePtr Compiler::fgMakeTmpArgNode(unsigned tmpVarNum FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(const bool passedInRegisters)) { LclVarDsc * varDsc = &lvaTable[tmpVarNum]; assert(varDsc->lvIsTemp); var_types type = varDsc->TypeGet(); // Create a copy of the temp to go into the late argument list GenTreePtr arg = gtNewLclvNode(tmpVarNum, type); GenTreePtr addrNode = nullptr; if (varTypeIsStruct(type)) { #if defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_) #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING arg->gtFlags |= GTF_DONT_CSE; // If it is passed in registers, don't get the address of the var. Make it a // field instead. It will be loaded in registers with putarg_reg tree in lower. if (passedInRegisters) { arg->ChangeOper(GT_LCL_FLD); arg->gtType = type; } else { arg = gtNewOperNode(GT_ADDR, type, arg); addrNode = arg; } #else // !FEATURE_UNIX_AMD64_STRUCT_PASSING unsigned structSize = lvaLclExactSize(tmpVarNum); switch (structSize) { case 1: type = TYP_BYTE; break; case 2: type = TYP_SHORT; break; #if defined (_TARGET_AMD64_) case 4: type = TYP_INT; break; #elif defined(_TARGET_ARM64_) case 3: case 4: type = TYP_INT; break; case 5: case 6: case 7: type = TYP_I_IMPL; break; #endif // defined (_TARGET_ARM64_) case 8: switch (*lvaGetGcLayout(tmpVarNum)) { case TYPE_GC_NONE: type = TYP_I_IMPL; break; case TYPE_GC_REF: type = TYP_REF; break; case TYPE_GC_BYREF: type = TYP_BYREF; break; default: unreached(); } break; default: break; } // If we didn't change the type of the struct, it means // its structure doesn't support to be passed directly through a // register, so we need to pass a pointer to the destination where // where we copied the struct to. if (type == varDsc->TypeGet()) { #if FEATURE_MULTIREG_ARGS #ifdef _TARGET_ARM64_ assert(varTypeIsStruct(type)); if (varDsc->lvIsMultiregStruct()) { // ToDo-ARM64: Consider using: arg->ChangeOper(GT_LCL_FLD); // as that is how FEATURE_UNIX_AMD64_STRUCT_PASSING works. // Create a GT_OBJ for the argument // This will be passed by value in two registers arg = gtNewOperNode(GT_ADDR, TYP_BYREF, arg); addrNode = arg; // Create an Obj of the temp to use it as a call argument. arg = gtNewObjNode(lvaGetStruct(tmpVarNum), arg); } else #endif // _TARGET_ARM64_ #endif // FEATURE_MULTIREG_ARGS { arg = gtNewOperNode(GT_ADDR, TYP_I_IMPL, arg); addrNode = arg; } } else // type was changed from a struct to a scalar type { arg->ChangeOper(GT_LCL_FLD); arg->gtType = type; } #endif // !FEATURE_UNIX_AMD64_STRUCT_PASSING #else // not (_TARGET_AMD64_ or _TARGET_ARM64_) // other targets, we pass the struct by value assert(varTypeIsStruct(type)); arg = gtNewOperNode(GT_ADDR, TYP_BYREF, arg); addrNode = arg; // Get a new Obj node temp to use it as a call argument arg = gtNewObjNode(lvaGetStruct(tmpVarNum), arg); arg->gtFlags |= GTF_EXCEPT; #endif // not (_TARGET_AMD64_ or _TARGET_ARM64_) } // (varTypeIsStruct(type)) if (addrNode != nullptr) { assert(addrNode->gtOper == GT_ADDR); // This will prevent this LclVar from being optimized away lvaSetVarAddrExposed(tmpVarNum); // the child of a GT_ADDR is required to have this flag set addrNode->gtOp.gtOp1->gtFlags |= GTF_DONT_CSE; } return arg; } void fgArgInfo::EvalArgsToTemps() { assert(argsSorted == true); unsigned regArgInx = 0; // Now go through the argument table and perform the necessary evaluation into temps GenTreeArgList* tmpRegArgNext = NULL; for (unsigned curInx = 0; curInx < argCount; curInx++) { fgArgTabEntryPtr curArgTabEntry = argTable[curInx]; GenTreePtr argx = curArgTabEntry->node; GenTreePtr setupArg = NULL; GenTreePtr defArg; #if !FEATURE_FIXED_OUT_ARGS // Only ever set for FEATURE_FIXED_OUT_ARGS assert(curArgTabEntry->needPlace == false); // On x86 and other archs that use push instructions to pass arguments: // Only the register arguments need to be replaced with placeholder nodes. // Stacked arguments are evaluated and pushed (or stored into the stack) in order. // if (curArgTabEntry->regNum == REG_STK) continue; #endif if (curArgTabEntry->needTmp) { unsigned tmpVarNum; if (curArgTabEntry->isTmp == true) { // Create a copy of the temp to go into the late argument list tmpVarNum = curArgTabEntry->tmpNum; defArg = compiler->fgMakeTmpArgNode( tmpVarNum FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(argTable[curInx]->structDesc.passedInRegisters)); // mark the original node as a late argument argx->gtFlags |= GTF_LATE_ARG; } else { // Create a temp assignment for the argument // Put the temp in the gtCallLateArgs list #ifdef DEBUG if (compiler->verbose) { printf("Argument with 'side effect'...\n"); compiler->gtDispTree(argx); } #endif #if defined(_TARGET_AMD64_) && !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) noway_assert(argx->gtType != TYP_STRUCT); #endif tmpVarNum = compiler->lvaGrabTemp(true DEBUGARG("argument with side effect")); if (argx->gtOper == GT_MKREFANY) { // For GT_MKREFANY, typically the actual struct copying does // not have any side-effects and can be delayed. So instead // of using a temp for the whole struct, we can just use a temp // for operand that that has a side-effect GenTreePtr operand; if ((argx->gtOp.gtOp2->gtFlags & GTF_ALL_EFFECT) == 0) { operand = argx->gtOp.gtOp1; // In the early argument evaluation, place an assignment to the temp // from the source operand of the mkrefany setupArg = compiler->gtNewTempAssign(tmpVarNum, operand); // Replace the operand for the mkrefany with the new temp. argx->gtOp.gtOp1 = compiler->gtNewLclvNode(tmpVarNum, operand->TypeGet()); } else if ((argx->gtOp.gtOp1->gtFlags & GTF_ALL_EFFECT) == 0) { operand = argx->gtOp.gtOp2; // In the early argument evaluation, place an assignment to the temp // from the source operand of the mkrefany setupArg = compiler->gtNewTempAssign(tmpVarNum, operand); // Replace the operand for the mkrefany with the new temp. argx->gtOp.gtOp2 = compiler->gtNewLclvNode(tmpVarNum, operand->TypeGet()); } } if (setupArg != NULL) { // Now keep the mkrefany for the late argument list defArg = argx; // Clear the side-effect flags because now both op1 and op2 have no side-effects defArg->gtFlags &= ~GTF_ALL_EFFECT; } else { setupArg = compiler->gtNewTempAssign(tmpVarNum, argx); #ifndef LEGACY_BACKEND if (compiler->fgOrder == Compiler::FGOrderLinear) { // We'll reference this temporary variable just once // when we perform the function call after // setting up this argument. LclVarDsc* varDsc = compiler->lvaTable + tmpVarNum; varDsc->lvRefCnt = 1; } #endif // !LEGACY_BACKEND if (setupArg->OperIsCopyBlkOp()) setupArg = compiler->fgMorphCopyBlock(setupArg); /* Create a copy of the temp to go to the late argument list */ defArg = compiler->gtNewLclvNode(tmpVarNum, genActualType(argx->gtType)); curArgTabEntry->isTmp = true; curArgTabEntry->tmpNum = tmpVarNum; #ifdef _TARGET_ARM_ // Previously we might have thought the local was promoted, and thus the 'COPYBLK' // might have left holes in the used registers (see // fgAddSkippedRegsInPromotedStructArg). // Too bad we're not that smart for these intermediate temps... if (isValidIntArgReg(curArgTabEntry->regNum) && (curArgTabEntry->numRegs > 1)) { regNumber argReg = curArgTabEntry->regNum; regMaskTP allUsedRegs = genRegMask(curArgTabEntry->regNum); for (unsigned i = 1; i < curArgTabEntry->numRegs; i++) { argReg = genRegArgNext(argReg); allUsedRegs |= genRegMask(argReg); } callTree->gtCall.gtCallRegUsedMask |= allUsedRegs; } #endif // _TARGET_ARM_ } /* mark the assignment as a late argument */ setupArg->gtFlags |= GTF_LATE_ARG; #ifdef DEBUG if (compiler->verbose) { printf("\n Evaluate to a temp:\n"); compiler->gtDispTree(setupArg); } #endif } } else // curArgTabEntry->needTmp == false { // On x86 - // Only register args are replaced with placeholder nodes // and the stack based arguments are evaluated and pushed in order. // // On Arm/x64 - When needTmp is false and needPlace is false, // the non-register arguments are evaluated and stored in order. // When needPlace is true we have a nested call that comes after // this argument so we have to replace it in the gtCallArgs list // (the initial argument evaluation list) with a placeholder. // if ((curArgTabEntry->regNum == REG_STK) && (curArgTabEntry->needPlace == false)) continue; /* No temp needed - move the whole node to the gtCallLateArgs list */ /* The argument is deferred and put in the late argument list */ defArg = argx; // Create a placeholder node to put in its place in gtCallLateArgs. // For a struct type we also need to record the class handle of the arg. CORINFO_CLASS_HANDLE clsHnd = NO_CLASS_HANDLE; #if defined(_TARGET_AMD64_) && !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) // All structs are either passed (and retyped) as integral types, OR they // are passed by reference. noway_assert(argx->gtType != TYP_STRUCT); #else // !defined(_TARGET_AMD64_) || defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) if (varTypeIsStruct(defArg)) { // Need a temp to walk any GT_COMMA nodes when searching for the clsHnd GenTreePtr defArgTmp = defArg; // The GT_OBJ may be be a child of a GT_COMMA. while (defArgTmp->gtOper == GT_COMMA) { defArgTmp = defArgTmp->gtOp.gtOp2; } assert(varTypeIsStruct(defArgTmp)); // We handle two opcodes: GT_MKREFANY and GT_OBJ. if (defArgTmp->gtOper == GT_MKREFANY) { clsHnd = compiler->impGetRefAnyClass(); } else if (defArgTmp->gtOper == GT_OBJ) { clsHnd = defArgTmp->AsObj()->gtClass; } else { BADCODE("Unhandled struct argument tree in fgMorphArgs"); } } #endif // !(defined(_TARGET_AMD64_) && !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)) setupArg = compiler->gtNewArgPlaceHolderNode(defArg->gtType, clsHnd); /* mark the placeholder node as a late argument */ setupArg->gtFlags |= GTF_LATE_ARG; #ifdef DEBUG if (compiler->verbose) { if (curArgTabEntry->regNum == REG_STK) { printf("Deferred stack argument :\n"); } else { printf("Deferred argument ('%s'):\n", getRegName(curArgTabEntry->regNum)); } compiler->gtDispTree(argx); printf("Replaced with placeholder node:\n"); compiler->gtDispTree(setupArg); } #endif } if (setupArg != NULL) { if (curArgTabEntry->parent) { GenTreePtr parent = curArgTabEntry->parent; /* a normal argument from the list */ noway_assert(parent->IsList()); noway_assert(parent->gtOp.gtOp1 == argx); parent->gtOp.gtOp1 = setupArg; } else { /* must be the gtCallObjp */ noway_assert(callTree->gtCall.gtCallObjp == argx); callTree->gtCall.gtCallObjp = setupArg; } } /* deferred arg goes into the late argument list */ if (tmpRegArgNext == NULL) { tmpRegArgNext = compiler->gtNewArgList(defArg); callTree->gtCall.gtCallLateArgs = tmpRegArgNext; } else { noway_assert(tmpRegArgNext->IsList()); noway_assert(tmpRegArgNext->Current()); tmpRegArgNext->gtOp.gtOp2 = compiler->gtNewArgList(defArg); tmpRegArgNext = tmpRegArgNext->Rest(); } curArgTabEntry->node = defArg; curArgTabEntry->lateArgInx = regArgInx++; } #ifdef DEBUG if (compiler->verbose) { printf("\nShuffled argument table: "); for (unsigned curInx = 0; curInx < argCount; curInx++) { fgArgTabEntryPtr curArgTabEntry = argTable[curInx]; if (curArgTabEntry->regNum != REG_STK) { printf("%s ", getRegName( curArgTabEntry->regNum )); } } printf("\n"); } #endif } void fgArgInfo::RecordStkLevel(unsigned stkLvl) { assert(!IsUninitialized(stkLvl)); this->stkLevel = stkLvl; } unsigned fgArgInfo::RetrieveStkLevel() { assert(!IsUninitialized(stkLevel)); return stkLevel; } // Return a conservative estimate of the stack size in bytes. // It will be used only on the intercepted-for-host code path to copy the arguments. int Compiler::fgEstimateCallStackSize(GenTreeCall* call) { int numArgs = 0; for (GenTreeArgList* args = call->gtCallArgs; args; args = args->Rest()) { numArgs++; } int numStkArgs; if (numArgs > MAX_REG_ARG) numStkArgs = numArgs - MAX_REG_ARG; else numStkArgs = 0; return numStkArgs * REGSIZE_BYTES; } //------------------------------------------------------------------------------ // fgMakeMultiUse : If the node is a local, clone it and increase the ref count // otherwise insert a comma form temp // // Arguments: // ppTree - a pointer to the child node we will be replacing with the comma expression that // evaluates ppTree to a temp and returns the result // // Return Value: // A fresh GT_LCL_VAR node referencing the temp which has not been used // // Assumption: // The result tree MUST be added to the tree structure since the ref counts are // already incremented. GenTree* Compiler::fgMakeMultiUse(GenTree** pOp) { GenTree* tree = *pOp; if (tree->IsLocal()) { auto result = gtClone(tree); if (lvaLocalVarRefCounted) { lvaTable[tree->gtLclVarCommon.gtLclNum].incRefCnts(compCurBB->getBBWeight(this), this); } return result; } else { GenTree* result = fgInsertCommaFormTemp(pOp); // At this point, *pOp is GT_COMMA(GT_ASG(V01, *pOp), V01) and result = V01 // Therefore, the ref count has to be incremented 3 times for *pOp and result, if result will // be added by the caller. if (lvaLocalVarRefCounted) { lvaTable[result->gtLclVarCommon.gtLclNum].incRefCnts(compCurBB->getBBWeight(this), this); lvaTable[result->gtLclVarCommon.gtLclNum].incRefCnts(compCurBB->getBBWeight(this), this); lvaTable[result->gtLclVarCommon.gtLclNum].incRefCnts(compCurBB->getBBWeight(this), this); } return result; } } //------------------------------------------------------------------------------ // fgInsertCommaFormTemp: Create a new temporary variable to hold the result of *ppTree, // and replace *ppTree with comma(asg(newLcl, *ppTree), newLcl) // // Arguments: // ppTree - a pointer to the child node we will be replacing with the comma expression that // evaluates ppTree to a temp and returns the result // // structType - value type handle if the temp created is of TYP_STRUCT. // // Return Value: // A fresh GT_LCL_VAR node referencing the temp which has not been used // GenTree* Compiler::fgInsertCommaFormTemp(GenTree** ppTree, CORINFO_CLASS_HANDLE structType /*= nullptr*/) { GenTree* subTree = *ppTree; unsigned lclNum = lvaGrabTemp(true DEBUGARG("fgInsertCommaFormTemp is creating a new local variable")); if (varTypeIsStruct(subTree)) { assert(structType != nullptr); lvaSetStruct(lclNum, structType, false); } // If subTree->TypeGet() == TYP_STRUCT, gtNewTempAssign() will create a GT_COPYBLK tree. // The type of GT_COPYBLK is TYP_VOID. Therefore, we should use subTree->TypeGet() for // setting type of lcl vars created. GenTree* asg = gtNewTempAssign(lclNum, subTree); GenTree* load = new (this, GT_LCL_VAR) GenTreeLclVar(subTree->TypeGet(), lclNum, BAD_IL_OFFSET); GenTree* comma = gtNewOperNode(GT_COMMA, subTree->TypeGet(), asg, load); *ppTree = comma; return new (this, GT_LCL_VAR) GenTreeLclVar(subTree->TypeGet(), lclNum, BAD_IL_OFFSET); } //------------------------------------------------------------------------ // fgMorphArgs: Walk and transform (morph) the arguments of a call // // Arguments: // callNode - the call for which we are doing the argument morphing // // Return Value: // Like most morph methods, this method returns the morphed node, // though in this case there are currently no scenarios where the // node itself is re-created. // // Notes: // This method is even less idempotent than most morph methods. // That is, it makes changes that should not be redone. It uses the existence // of gtCallLateArgs (the late arguments list) to determine if it has // already done that work. // // The first time it is called (i.e. during global morphing), this method // computes the "late arguments". This is when it determines which arguments // need to be evaluated to temps prior to the main argument setup, and which // can be directly evaluated into the argument location. It also creates a // second argument list (gtCallLateArgs) that does the final placement of the // arguments, e.g. into registers or onto the stack. // // The "non-late arguments", aka the gtCallArgs, are doing the in-order // evaluation of the arguments that might have side-effects, such as embedded // assignments, calls or possible throws. In these cases, it and earlier // arguments must be evaluated to temps. // // On targets with a fixed outgoing argument area (FEATURE_FIXED_OUT_ARGS), // if we have any nested calls, we need to defer the copying of the argument // into the fixed argument area until after the call. If the argument did not // otherwise need to be computed into a temp, it is moved to gtCallLateArgs and // replaced in the "early" arg list (gtCallArgs) with a placeholder node. #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:21000) // Suppress PREFast warning about overly large function #endif GenTreeCall* Compiler::fgMorphArgs(GenTreeCall* callNode) { GenTreeCall* call = callNode->AsCall(); GenTreePtr args; GenTreePtr argx; unsigned flagsSummary = 0; unsigned genPtrArgCntSav = fgPtrArgCntCur; unsigned argIndex = 0; unsigned intArgRegNum = 0; unsigned fltArgRegNum = 0; regMaskTP argSkippedRegMask = RBM_NONE; #if defined(_TARGET_ARM_) || defined(_TARGET_AMD64_) regMaskTP fltArgSkippedRegMask = RBM_NONE; #endif #if defined(_TARGET_X86_) unsigned maxRegArgs = MAX_REG_ARG; // X86: non-const, must be calculated #else const unsigned maxRegArgs = MAX_REG_ARG; // other arch: fixed constant number #endif unsigned argSlots = 0; unsigned nonRegPassedStructSlots = 0; bool lateArgsComputed = (call->gtCallLateArgs != nullptr); bool callHasRetBuffArg = ((call->gtCallMoreFlags & GTF_CALL_M_RETBUFFARG) != 0); #ifndef _TARGET_X86_ // i.e. _TARGET_AMD64_ or _TARGET_ARM_ bool callIsVararg = call->IsVarargs(); #endif bool hasNonStandardArg = false; #ifndef LEGACY_BACKEND // data structure for keeping track of non-standard args we insert // (args that have a special meaning and are not passed following the normal // calling convention or even in the normal arg regs. struct NonStandardArg { regNumber reg; GenTree* node; }; ArrayStack<NonStandardArg> nonStandardArgs(this, 2); #endif // !LEGACY_BACKEND // Process the late arguments (which were determined by a previous caller). // Do this before resetting fgPtrArgCntCur as fgMorphTree(call->gtCallLateArgs) // may need to refer to it. if (lateArgsComputed) { // We need to reMorph the gtCallLateArgs early since that is what triggers // the expression folding and we need to have the final folded gtCallLateArgs // available when we call RemorphRegArg so that we correctly update the fgArgInfo // with the folded tree that represents the final optimized argument nodes. // // However if a range-check needs to be generated for any of these late // arguments we also need to "know" what the stack depth will be when we generate // code to branch to the throw range check failure block as that is part of the // GC information contract for that block. // // Since the late arguments are evaluated last we have pushed all of the // other arguments on the stack before we evaluate these late arguments, // so we record the stack depth on the first morph call when lateArgsComputed // was false (via RecordStkLevel) and then retrieve that value here (via RetrieveStkLevel) // unsigned callStkLevel = call->fgArgInfo->RetrieveStkLevel(); fgPtrArgCntCur += callStkLevel; call->gtCallLateArgs = fgMorphTree(call->gtCallLateArgs)->AsArgList(); flagsSummary |= call->gtCallLateArgs->gtFlags; fgPtrArgCntCur -= callStkLevel; assert(call->fgArgInfo != nullptr); call->fgArgInfo->RemorphReset(); } else { // First we need to count the args unsigned numArgs = 0; if (call->gtCallObjp) numArgs++; for (args = call->gtCallArgs; (args != nullptr); args = args->gtOp.gtOp2) { numArgs++; } // insert nonstandard args (outside the calling convention) #if !defined(LEGACY_BACKEND) && !defined(_TARGET_X86_) // TODO-X86-CQ: Currently RyuJIT/x86 passes args on the stack, so this is not needed. // If/when we change that, the following code needs to be changed to correctly support the (TBD) managed calling // convention for x86/SSE. if (!lateArgsComputed) { if (call->IsUnmanaged()) { assert(!call->gtCallCookie); // Add a conservative estimate of the stack size in a special parameter (r11) at the call site. // It will be used only on the intercepted-for-host code path to copy the arguments. GenTree* cns = new (this, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, fgEstimateCallStackSize(call)); call->gtCallArgs = gtNewListNode(cns, call->gtCallArgs); NonStandardArg nsa = {REG_PINVOKE_COOKIE_PARAM, cns}; numArgs++; nonStandardArgs.Push(nsa); } else if (call->IsVirtualStub() && (call->gtCallType == CT_INDIRECT) && !call->IsTailCallViaHelper()) { // indirect VSD stubs need the base of the indirection cell to be // passed in addition. At this point that is the value in gtCallAddr. // The actual call target will be derived from gtCallAddr in call // lowering. // If it is a VSD call getting dispatched via tail call helper, // fgMorphTailCall() would materialize stub addr as an additional // parameter added to the original arg list and hence no need to // add as a non-standard arg. GenTree* arg = call->gtCallAddr; if (arg->OperIsLocal()) { arg = gtClone(arg, true); } else { call->gtCallAddr = fgInsertCommaFormTemp(&arg); call->gtFlags |= GTF_ASG; } noway_assert(arg != nullptr); // And push the stub address onto the list of arguments call->gtCallArgs = gtNewListNode(arg, call->gtCallArgs); numArgs++; NonStandardArg nsa = {REG_VIRTUAL_STUB_PARAM, arg}; nonStandardArgs.Push(nsa); } else if (call->gtCallType == CT_INDIRECT && call->gtCallCookie) { assert(!call->IsUnmanaged()); // put cookie into R11 GenTree* arg = call->gtCallCookie; noway_assert(arg != nullptr); call->gtCallCookie = nullptr; call->gtCallArgs = gtNewListNode(arg, call->gtCallArgs); numArgs++; NonStandardArg nsa = {REG_PINVOKE_COOKIE_PARAM, arg}; nonStandardArgs.Push(nsa); // put destination into R10 arg = gtClone(call->gtCallAddr, true); call->gtCallArgs = gtNewListNode(arg, call->gtCallArgs); numArgs++; NonStandardArg nsa2 = {REG_PINVOKE_TARGET_PARAM, arg}; nonStandardArgs.Push(nsa2); // finally change this call to a helper call call->gtCallType = CT_HELPER; call->gtCallMethHnd = eeFindHelper(CORINFO_HELP_PINVOKE_CALLI); } } #endif // !defined(LEGACY_BACKEND) && !defined(_TARGET_X86_) // Allocate the fgArgInfo for the call node; // call->fgArgInfo = new (this, CMK_Unknown) fgArgInfo(this, call, numArgs); } fgFixupStructReturn(call); /* First we morph the argument subtrees ('this' pointer, arguments, etc.). * During the first call to fgMorphArgs we also record the * information about late arguments we have in 'fgArgInfo'. * This information is used later to contruct the gtCallLateArgs */ /* Process the 'this' argument value, if present */ argx = call->gtCallObjp; if (argx) { argx = fgMorphTree(argx); call->gtCallObjp = argx; flagsSummary |= argx->gtFlags; assert(call->gtCallType == CT_USER_FUNC || call->gtCallType == CT_INDIRECT); assert(argIndex == 0); /* We must fill in or update the argInfo table */ if (!lateArgsComputed) { assert(varTypeIsGC(call->gtCallObjp->gtType) || (call->gtCallObjp->gtType == TYP_I_IMPL)); /* this is a register argument - put it in the table */ call->fgArgInfo->AddRegArg(argIndex, argx, NULL, genMapIntRegArgNumToRegNum(intArgRegNum), 1, 1 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING , false, REG_STK, nullptr #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING ); } else { /* this is a register argument - possibly update it in the table */ call->fgArgInfo->RemorphRegArg(argIndex, argx, NULL, genMapIntRegArgNumToRegNum(intArgRegNum), 1, 1); } // this can't be a struct. assert(argx->gtType != TYP_STRUCT); /* Increment the argument register count and argument index */ if (!varTypeIsFloating(argx->gtType)) { intArgRegNum++; #if defined(_TARGET_AMD64_) && !defined(UNIX_AMD64_ABI) fltArgSkippedRegMask |= genMapArgNumToRegMask(fltArgRegNum, TYP_FLOAT); fltArgRegNum++; #endif } else { fltArgRegNum++; #if defined(_TARGET_AMD64_) && !defined(UNIX_AMD64_ABI) argSkippedRegMask |= genMapArgNumToRegMask(intArgRegNum, TYP_I_IMPL); intArgRegNum++; #endif } argIndex++; argSlots++; } #ifdef _TARGET_X86_ // Compute the maximum number of arguments that can be passed in registers. // For X86 we handle the varargs and unmanaged calling conventions if (call->gtFlags & GTF_CALL_POP_ARGS) { noway_assert(intArgRegNum < MAX_REG_ARG); // No more register arguments for varargs (CALL_POP_ARGS) maxRegArgs = intArgRegNum; // Add in the ret buff arg if (callHasRetBuffArg) maxRegArgs++; } #if INLINE_NDIRECT if (call->IsUnmanaged()) { noway_assert(intArgRegNum == 0); if (call->gtCallMoreFlags & GTF_CALL_M_UNMGD_THISCALL) { noway_assert(call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_I_IMPL || call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_BYREF || call->gtCallArgs->gtOp.gtOp1->gtOper == GT_NOP); // the arg was already morphed to a register (fgMorph called twice) maxRegArgs = 1; } else { maxRegArgs = 0; } // Add in the ret buff arg if (callHasRetBuffArg) maxRegArgs++; } #endif // INLINE_NDIRECT #endif // _TARGET_X86_ /* Morph the user arguments */ #if defined(_TARGET_ARM_) // The ARM ABI has a concept of back-filling of floating-point argument registers, according // to the "Procedure Call Standard for the ARM Architecture" document, especially // section 6.1.2.3 "Parameter passing". Back-filling is where floating-point argument N+1 can // appear in a lower-numbered register than floating point argument N. That is, argument // register allocation is not strictly increasing. To support this, we need to keep track of unused // floating-point argument registers that we can back-fill. We only support 4-byte float and // 8-byte double types, and one to four element HFAs composed of these types. With this, we will // only back-fill single registers, since there is no way with these types to create // an alignment hole greater than one register. However, there can be up to 3 back-fill slots // available (with 16 FP argument registers). Consider this code: // // struct HFA { float x, y, z; }; // a three element HFA // void bar(float a1, // passed in f0 // double a2, // passed in f2/f3; skip f1 for alignment // HFA a3, // passed in f4/f5/f6 // double a4, // passed in f8/f9; skip f7 for alignment. NOTE: it doesn't fit in the f1 back-fill slot // HFA a5, // passed in f10/f11/f12 // double a6, // passed in f14/f15; skip f13 for alignment. NOTE: it doesn't fit in the f1 or f7 back-fill slots // float a7, // passed in f1 (back-filled) // float a8, // passed in f7 (back-filled) // float a9, // passed in f13 (back-filled) // float a10) // passed on the stack in [OutArg+0] // // Note that if we ever support FP types with larger alignment requirements, then there could // be more than single register back-fills. // // Once we assign a floating-pointer register to the stack, they all must be on the stack. // See "Procedure Call Standard for the ARM Architecture", section 6.1.2.3, "The back-filling // continues only so long as no VFP CPRC has been allocated to a slot on the stack." // We set anyFloatStackArgs to true when a floating-point argument has been assigned to the stack // and prevent any additional floating-point arguments from going in registers. bool anyFloatStackArgs = false; #endif // _TARGET_ARM_ #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING bool nonRegPassableStruct = false; SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR structDesc; #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING bool hasStructArgument = false; for (args = call->gtCallArgs; args; args = args->gtOp.gtOp2) { GenTreePtr * parentArgx = &args->gtOp.gtOp1; #if FEATURE_MULTIREG_ARGS if (!hasStructArgument) { hasStructArgument = varTypeIsStruct(args->gtOp.gtOp1); } #endif // FEATURE_MULTIREG_ARGS argx = fgMorphTree(*parentArgx); *parentArgx = argx; flagsSummary |= argx->gtFlags; assert(args->IsList()); assert(argx == args->Current()); /* Change the node to TYP_I_IMPL so we don't report GC info * NOTE: We deferred this from the importer because of the inliner */ if (argx->IsVarAddr()) argx->gtType = TYP_I_IMPL; bool passUsingFloatRegs; unsigned argAlign = 1; #ifdef _TARGET_ARM_ var_types hfaType = GetHfaType(argx); bool isHfaArg = varTypeIsFloating(hfaType); #endif // _TARGET_ARM_ unsigned size = 0; CORINFO_CLASS_HANDLE copyBlkClass = NULL; bool isRegArg = false; fgArgTabEntryPtr argEntry = NULL; if (lateArgsComputed) { argEntry = gtArgEntryByArgNum(call, argIndex); } #ifdef _TARGET_ARM_ bool passUsingIntRegs; if (lateArgsComputed) { passUsingFloatRegs = isValidFloatArgReg(argEntry->regNum); passUsingIntRegs = isValidIntArgReg(argEntry->regNum); } else { passUsingFloatRegs = !callIsVararg && (isHfaArg || varTypeIsFloating(argx)); passUsingIntRegs = passUsingFloatRegs ? false : (intArgRegNum < MAX_REG_ARG); } GenTreePtr curArg = argx; // If late args have already been computed, use the node in the argument table. if (argEntry != NULL && argEntry->isTmp) { curArg = argEntry->node; } // We don't use the "size" return value from InferOpSizeAlign(). codeGen->InferOpSizeAlign(curArg, &argAlign); argAlign = roundUp(argAlign, TARGET_POINTER_SIZE); argAlign /= TARGET_POINTER_SIZE; if (argAlign == 2) { if (passUsingFloatRegs) { if (fltArgRegNum % 2 == 1) { fltArgSkippedRegMask |= genMapArgNumToRegMask(fltArgRegNum, TYP_FLOAT); fltArgRegNum ++; } } else if (passUsingIntRegs) { if (intArgRegNum % 2 == 1) { argSkippedRegMask |= genMapArgNumToRegMask(intArgRegNum, TYP_I_IMPL); intArgRegNum ++; } } if (argSlots % 2 == 1) { argSlots ++; } } #elif defined(_TARGET_ARM64_) // TODO-ARM64-NYI: HFA/HVA if (lateArgsComputed) { passUsingFloatRegs = isValidFloatArgReg(argEntry->regNum); } else { passUsingFloatRegs = !callIsVararg && varTypeIsFloating(argx); } #elif defined(_TARGET_AMD64_) #if defined(UNIX_AMD64_ABI) if (lateArgsComputed) { passUsingFloatRegs = isValidFloatArgReg(argEntry->regNum); } else { passUsingFloatRegs = varTypeIsFloating(argx); } bool passUsingIntRegs; passUsingIntRegs = passUsingFloatRegs ? false : (intArgRegNum < MAX_REG_ARG); #else // !UNIX_AMD64_ABI passUsingFloatRegs = varTypeIsFloating(argx); #endif // !UNIX_AMD64_ABI #elif defined(_TARGET_X86_) passUsingFloatRegs = false; #else #error Unsupported or unset target architecture #endif // _TARGET_* bool isBackFilled = false; unsigned nextFltArgRegNum = fltArgRegNum; // This is the next floating-point argument register number to use var_types structBaseType = TYP_STRUCT; #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) unsigned int structFloatRegs = 0; unsigned int structIntRegs = 0; #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) bool isStructArg = varTypeIsStruct(argx); if (lateArgsComputed) { #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) // Get the struct description for the already completed struct argument. fgArgTabEntryPtr fgEntryPtr = gtArgEntryByNode(call, argx); assert(fgEntryPtr != nullptr); // As described in few other places, this can happen when the argx was morphed // into an arg setup node - COPYBLK. The COPYBLK has always a type of void. // In such case the fgArgTabEntry keeps track of whether the original node (before morphing) // was a struct and the struct classification. isStructArg = fgEntryPtr->isStruct; if (isStructArg) { structDesc.CopyFrom(fgEntryPtr->structDesc); } #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) assert(argEntry != NULL); if (argEntry->IsBackFilled()) { isRegArg = true; size = argEntry->numRegs; nextFltArgRegNum = genMapFloatRegNumToRegArgNum(argEntry->regNum); assert(size == 1); isBackFilled = true; } else if (argEntry->regNum == REG_STK) { isRegArg = false; assert(argEntry->numRegs == 0); size = argEntry->numSlots; } else { isRegArg = true; assert(argEntry->numRegs > 0); size = argEntry->numRegs + argEntry->numSlots; } // This size has now been computed assert(size != 0); } else { // // Figure out the size of the argument. This is either in number of registers, or number of register-sized // stack slots, or both if the argument is split between the registers and the stack. // if (argx->IsArgPlaceHolderNode() || (!isStructArg)) { #if defined(_TARGET_AMD64_) #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING if (!isStructArg) { size = 1; // On AMD64, all primitives fit in a single (64-bit) 'slot' } else { size = (unsigned)(roundUp(info.compCompHnd->getClassSize(argx->gtArgPlace.gtArgPlaceClsHnd), TARGET_POINTER_SIZE)) / TARGET_POINTER_SIZE; eeGetSystemVAmd64PassStructInRegisterDescriptor(argx->gtArgPlace.gtArgPlaceClsHnd, &structDesc); } #else // !FEATURE_UNIX_AMD64_STRUCT_PASSING size = 1; // On AMD64, all primitives fit in a single (64-bit) 'slot' #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING #elif defined(_TARGET_ARM64_) if (isStructArg) { // Structs are either passed in 1 or 2 (64-bit) slots size = (unsigned)(roundUp(info.compCompHnd->getClassSize(argx->gtArgPlace.gtArgPlaceClsHnd), TARGET_POINTER_SIZE)) / TARGET_POINTER_SIZE; if (size > 2) { size = 1; // Large structs are passed by reference (to a copy) } // Note that there are some additional rules for size=2 structs, // (i.e they cannot be split betwen registers and the stack) } else { size = 1; // On ARM64, all primitive types fit in a single (64-bit) 'slot' } #elif defined(_TARGET_ARM_) if (isStructArg) { size = (unsigned)(roundUp(info.compCompHnd->getClassSize(argx->gtArgPlace.gtArgPlaceClsHnd), TARGET_POINTER_SIZE)) / TARGET_POINTER_SIZE; } else { // The typical case size = genTypeStSz(argx->gtType); } #elif defined(_TARGET_X86_) size = genTypeStSz(argx->gtType); #else #error Unsupported or unset target architecture #endif // _TARGET_XXX_ } #ifdef _TARGET_ARM_ else if (isHfaArg) { size = GetHfaSlots(argx); } #endif else // struct type { // We handle two opcodes: GT_MKREFANY and GT_OBJ if (argx->gtOper == GT_MKREFANY) { if (varTypeIsStruct(argx)) { isStructArg = true; } #ifdef _TARGET_AMD64_ #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) if (varTypeIsStruct(argx)) { size = info.compCompHnd->getClassSize(impGetRefAnyClass()); unsigned roundupSize = (unsigned)roundUp(size, TARGET_POINTER_SIZE); size = roundupSize / TARGET_POINTER_SIZE; eeGetSystemVAmd64PassStructInRegisterDescriptor(impGetRefAnyClass(), &structDesc); } else #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) { size = 1; } #else size = 2; #endif } else { // GT_OBJ case GenTreePtr argObj = argx; GenTreePtr* parentOfArgObj = parentArgx; assert(args->IsList()); assert(argx == args->Current()); /* The GT_OBJ may be be a child of a GT_COMMA */ while (argObj->gtOper == GT_COMMA) { parentOfArgObj = &argObj->gtOp.gtOp2; argObj = argObj->gtOp.gtOp2; } if (argObj->gtOper != GT_OBJ) BADCODE("illegal argument tree in fgMorphArgs"); CORINFO_CLASS_HANDLE objClass = argObj->gtObj.gtClass; #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING eeGetSystemVAmd64PassStructInRegisterDescriptor(objClass, &structDesc); #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING unsigned originalSize = info.compCompHnd->getClassSize(objClass); originalSize = (originalSize == 0 ? TARGET_POINTER_SIZE : originalSize); unsigned roundupSize = (unsigned)roundUp(originalSize, TARGET_POINTER_SIZE); #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING // On System V OS-es a struct is never passed by reference. // It is either passed by value on the stack or in registers. bool passStructInRegisters = false; #else // !FEATURE_UNIX_AMD64_STRUCT_PASSING bool passStructByRef = false; #endif // !FEATURE_UNIX_AMD64_STRUCT_PASSING #ifndef _TARGET_X86_ #ifndef FEATURE_UNIX_AMD64_STRUCT_PASSING // Check for struct argument with size 1, 2, 4 or 8 bytes // As we can optimize these by turning them into a GT_IND of the correct type if ((originalSize > TARGET_POINTER_SIZE) || ((originalSize & (originalSize - 1)) != 0)) #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING { // Normalize 'size' to the number of pointer sized items // 'size' is the number of register slots that we will use to pass the argument size = roundupSize / TARGET_POINTER_SIZE; #if defined(_TARGET_AMD64_) #ifndef FEATURE_UNIX_AMD64_STRUCT_PASSING size = 1; // This must be copied to a temp and passed by address passStructByRef = true; copyBlkClass = objClass; #else // FEATURE_UNIX_AMD64_STRUCT_PASSING if (!structDesc.passedInRegisters) { passStructInRegisters = false; copyBlkClass = NO_CLASS_HANDLE; } else { // The objClass is used to materialize the struct on stack. passStructInRegisters = true; copyBlkClass = objClass; } #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING #elif defined(_TARGET_ARM64_) if (size > 2) { size = 1; // This must be copied to a temp and passed by address passStructByRef = true; copyBlkClass = objClass; } #endif #ifdef _TARGET_ARM_ // If we're passing a promoted struct local var, // we may need to skip some registers due to alignment; record those. GenTreePtr lclVar = fgIsIndirOfAddrOfLocal(argObj); if (lclVar != NULL) { LclVarDsc* varDsc = &lvaTable[lclVar->gtLclVarCommon.gtLclNum]; if (varDsc->lvPromoted) { assert(argObj->OperGet() == GT_OBJ); if (lvaGetPromotionType(varDsc) == PROMOTION_TYPE_INDEPENDENT) { fgAddSkippedRegsInPromotedStructArg(varDsc, intArgRegNum, &argSkippedRegMask); } } } #endif // _TARGET_ARM_ } #ifndef FEATURE_UNIX_AMD64_STRUCT_PASSING else { // change our GT_OBJ into a GT_IND of the correct type. structBaseType = argOrReturnTypeForStruct(originalSize, objClass, false /* forReturn */); // We've already ensured above that size is a power of 2, and less than pointer size. noway_assert(structBaseType != TYP_UNKNOWN); argObj->ChangeOper(GT_IND); // Now see if we can fold *(&X) into X if (argObj->gtOp.gtOp1->gtOper == GT_ADDR) { GenTreePtr temp = argObj->gtOp.gtOp1->gtOp.gtOp1; // Keep the DONT_CSE flag in sync // (as the addr always marks it for its op1) temp->gtFlags &= ~GTF_DONT_CSE; temp->gtFlags |= (argObj->gtFlags & GTF_DONT_CSE); DEBUG_DESTROY_NODE(argObj->gtOp.gtOp1); // GT_ADDR DEBUG_DESTROY_NODE(argObj); // GT_IND argObj = temp; *parentOfArgObj = temp; // If the OBJ had been the top level node, we've now changed argx. if (parentOfArgObj == parentArgx) argx = temp; } if (argObj->gtOper == GT_LCL_VAR) { unsigned lclNum = argObj->gtLclVarCommon.gtLclNum; LclVarDsc * varDsc = &lvaTable[lclNum]; if (varDsc->lvPromoted) { if (varDsc->lvFieldCnt == 1) { // get the first and only promoted field LclVarDsc * fieldVarDsc = &lvaTable[varDsc->lvFieldLclStart]; if (genTypeSize(fieldVarDsc->TypeGet()) >= originalSize) { // we will use the first and only promoted field argObj->gtLclVarCommon.SetLclNum(varDsc->lvFieldLclStart); if (varTypeCanReg(fieldVarDsc->TypeGet()) && (genTypeSize(fieldVarDsc->TypeGet()) == originalSize)) { // Just use the existing field's type argObj->gtType = fieldVarDsc->TypeGet(); } else { // Can't use the existing field's type, so use GT_LCL_FLD to swizzle // to a new type argObj->ChangeOper(GT_LCL_FLD); argObj->gtType = structBaseType; } assert(varTypeCanReg(argObj->TypeGet())); assert(copyBlkClass == NO_CLASS_HANDLE); } else { // use GT_LCL_FLD to swizzle the single field struct to a new type lvaSetVarDoNotEnregister(lclNum DEBUG_ARG(DNER_LocalField)); argObj->ChangeOper(GT_LCL_FLD); argObj->gtType = structBaseType; } } else { // The struct fits into a single register, but it has been promoted into its // constituent fields, and so we have to re-assemble it copyBlkClass = objClass; #ifdef _TARGET_ARM_ // Alignment constraints may cause us not to use (to "skip") some argument registers. // Add those, if any, to the skipped (int) arg reg mask. fgAddSkippedRegsInPromotedStructArg(varDsc, intArgRegNum, &argSkippedRegMask); #endif // _TARGET_ARM_ } } else if (!varTypeIsIntegralOrI(varDsc->TypeGet())) { // Not a promoted struct, so just swizzle the type by using GT_LCL_FLD argObj->ChangeOper(GT_LCL_FLD); argObj->gtType = structBaseType; } } else { // Not a GT_LCL_VAR, so we can just change the type on the node argObj->gtType = structBaseType; } assert(varTypeCanReg(argObj->TypeGet()) || ((copyBlkClass != NO_CLASS_HANDLE) && varTypeIsIntegral(structBaseType))); size = 1; } #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING #endif // not _TARGET_X86_ // We still have a struct unless we converted the GT_OBJ into a GT_IND above... if ((structBaseType == TYP_STRUCT) && #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) !passStructInRegisters #else // !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) !passStructByRef #endif // !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) ) { // if the valuetype size is not a multiple of sizeof(void*), // we must copyblk to a temp before doing the obj to avoid // the obj reading memory past the end of the valuetype #if defined(_TARGET_X86_) && !defined(LEGACY_BACKEND) // TODO-X86-CQ: [1091733] Revisit for small structs, we should use push instruction copyBlkClass = objClass; size = roundupSize / TARGET_POINTER_SIZE; // Normalize size to number of pointer sized items #else // !defined(_TARGET_X86_) || defined(LEGACY_BACKEND) if (roundupSize > originalSize) { copyBlkClass = objClass; // There are a few special cases where we can omit using a CopyBlk // where we normally would need to use one. GenTreePtr objAddr = argObj->gtObj.gtOp1; if (objAddr->gtOper == GT_ADDR) { // exception : no need to use CopyBlk if the valuetype is on the stack if (objAddr->gtFlags & GTF_ADDR_ONSTACK) { copyBlkClass = NO_CLASS_HANDLE; } // exception : no need to use CopyBlk if the valuetype is already a struct local else if (objAddr->gtOp.gtOp1->gtOper == GT_LCL_VAR) { copyBlkClass = NO_CLASS_HANDLE; } } } size = roundupSize / TARGET_POINTER_SIZE; // Normalize size to number of pointer sized items #endif // !defined(_TARGET_X86_) || defined(LEGACY_BACKEND) } } } // The 'size' value has now must have been set. (the original value of zero is an invalid value) assert(size != 0); // // Figure out if the argument will be passed in a register. // bool passedInRegisters = true; #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING passedInRegisters = !isStructArg; if (!passedInRegisters) { if (structDesc.passedInRegisters) { passedInRegisters = true; } else { passedInRegisters = false; } } #endif if (passedInRegisters && isRegParamType(genActualType(argx->TypeGet()))) { #ifdef _TARGET_ARM_ if (passUsingFloatRegs) { // First, see if it can be back-filled if (!anyFloatStackArgs && // Is it legal to back-fill? (We haven't put any FP args on the stack yet) (fltArgSkippedRegMask != RBM_NONE) && // Is there an available back-fill slot? (size == 1)) // The size to back-fill is one float register { // Back-fill the register. isBackFilled = true; regMaskTP backFillBitMask = genFindLowestBit(fltArgSkippedRegMask); fltArgSkippedRegMask &= ~backFillBitMask; // Remove the back-filled register(s) from the skipped mask nextFltArgRegNum = genMapFloatRegNumToRegArgNum(genRegNumFromMask(backFillBitMask)); assert(nextFltArgRegNum < MAX_FLOAT_REG_ARG); } // Does the entire float, double, or HFA fit in the FP arg registers? // Check if the last register needed is still in the argument register range. isRegArg = (nextFltArgRegNum + size - 1) < MAX_FLOAT_REG_ARG; if (!isRegArg) { anyFloatStackArgs = true; } } else { isRegArg = intArgRegNum < MAX_REG_ARG; } #elif _TARGET_ARM64_ if (passUsingFloatRegs) { // Check if the last register needed is still in the fp argument register range. isRegArg = (nextFltArgRegNum + (size - 1)) < MAX_FLOAT_REG_ARG; } else { // Check if the last register needed is still in the int argument register range. isRegArg = (intArgRegNum + (size - 1)) < maxRegArgs; } #else // not _TARGET_ARM_ or _TARGET_ARM64_ #if defined(UNIX_AMD64_ABI) #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) // Here a struct can be passed in register following the classifications of its members and size. // Now make sure there are actually enough registers to do so. if (isStructArg) { for (unsigned int i = 0; i < structDesc.eightByteCount; i++) { if (structDesc.IsIntegralSlot(i)) { structIntRegs++; } else if (structDesc.IsSseSlot(i)) { structFloatRegs++; } } if (((nextFltArgRegNum + structFloatRegs) > MAX_FLOAT_REG_ARG) || ((intArgRegNum + structIntRegs) > MAX_REG_ARG)) { isRegArg = false; nonRegPassableStruct = true; } else { isRegArg = true; nonRegPassableStruct = false; } } else #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) { if (passUsingFloatRegs) { isRegArg = nextFltArgRegNum < MAX_FLOAT_REG_ARG; } else { isRegArg = intArgRegNum < MAX_REG_ARG; } } #else // !defined(UNIX_AMD64_ABI) isRegArg = (intArgRegNum+(size-1)) < maxRegArgs; #endif // !defined(UNIX_AMD64_ABI) #endif // _TARGET_ARM_ } else { isRegArg = false; #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING nonRegPassableStruct = true; #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING } } // // Now we know if the argument goes in registers or not and how big it is, // whether we had to just compute it or this is a re-morph call and we looked it up. // #ifdef _TARGET_ARM_ // If we ever allocate a floating point argument to the stack, then all // subsequent HFA/float/double arguments go on the stack. if (!isRegArg && passUsingFloatRegs) { for (; fltArgRegNum < MAX_FLOAT_REG_ARG; ++fltArgRegNum) { fltArgSkippedRegMask |= genMapArgNumToRegMask(fltArgRegNum, TYP_FLOAT); } } // If we think we're going to split a struct between integer registers and the stack, check to // see if we've already assigned a floating-point arg to the stack. if (isRegArg && // We decided above to use a register for the argument !passUsingFloatRegs && // We're using integer registers (intArgRegNum + size > MAX_REG_ARG) && // We're going to split a struct type onto registers and stack anyFloatStackArgs) // We've already used the stack for a floating-point argument { isRegArg = false; // Change our mind; don't pass this struct partially in registers // Skip the rest of the integer argument registers for (; intArgRegNum < MAX_REG_ARG; ++intArgRegNum) { argSkippedRegMask |= genMapArgNumToRegMask(intArgRegNum, TYP_I_IMPL); } } #endif // _TARGET_ARM_ if (isRegArg) { regNumber nextRegNum = REG_STK; #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) regNumber nextOtherRegNum = REG_STK; if (isStructArg && structDesc.passedInRegisters) { // It is a struct passed in registers. Assign the next available register. unsigned int curIntReg = intArgRegNum; unsigned int curFloatReg = nextFltArgRegNum; for (unsigned int i = 0; i < structDesc.eightByteCount; i++) { if (structDesc.IsIntegralSlot(i)) { if (i == 0) { nextRegNum = genMapIntRegArgNumToRegNum(curIntReg); // For non-completed args the counters are incremented already // in the !lateArgsComputed above. if (lateArgsComputed) { structIntRegs++; } } else if (i == 1) { nextOtherRegNum = genMapIntRegArgNumToRegNum(curIntReg); if (lateArgsComputed) { structIntRegs++; } } else { assert(false && "fgMorphArgs Invalid index for int classification."); } curIntReg++; } else if (structDesc.IsSseSlot(i)) { if (i == 0) { nextRegNum = genMapFloatRegArgNumToRegNum(curFloatReg); if (lateArgsComputed) { structFloatRegs++; } } else if (i == 1) { nextOtherRegNum = genMapFloatRegArgNumToRegNum(curFloatReg); if (lateArgsComputed) { structFloatRegs++; } } else { assert(false && "fgMorphArgs Invalid index for SSE classification."); } curFloatReg++; } } } else #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) { // fill in or update the argInfo table nextRegNum = passUsingFloatRegs ? genMapFloatRegArgNumToRegNum(nextFltArgRegNum) : genMapIntRegArgNumToRegNum(intArgRegNum); } #ifdef _TARGET_AMD64_ #ifndef FEATURE_UNIX_AMD64_STRUCT_PASSING assert(size == 1); #endif #endif #ifndef LEGACY_BACKEND // If there are nonstandard args (outside the calling convention) they were inserted above // and noted them in a table so we can recognize them here and build their argInfo. // // They should not affect the placement of any other args or stack space required. // Example: on AMD64 R10 and R11 are used for indirect VSD (generic interface) and cookie calls. bool nonStandardFound = false; for (int i=0; i<nonStandardArgs.Height(); i++) { hasNonStandardArg = true; if (argx == nonStandardArgs.Index(i).node) { fgArgTabEntry* argEntry = call->fgArgInfo->AddRegArg(argIndex, argx, args, nonStandardArgs.Index(i).reg, size, argAlign #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) , isStructArg, nextOtherRegNum, &structDesc #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) ); argEntry->isNonStandard = true; argIndex++; nonStandardFound = true; break; } } if (nonStandardFound) continue; #endif // !LEGACY_BACKEND if (!lateArgsComputed) { // This is a register argument - put it in the table fgArgTabEntryPtr newArg = call->fgArgInfo->AddRegArg(argIndex, argx, args, nextRegNum, size, argAlign #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) , isStructArg, nextOtherRegNum, &structDesc #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) ); (void)newArg; //prevent "unused variable" error from GCC #ifdef _TARGET_ARM_ newArg->SetIsHfaRegArg(passUsingFloatRegs && isHfaArg); // Note that an HFA is passed in int regs for varargs newArg->SetIsBackFilled(isBackFilled); #endif // _TARGET_ARM_ } else { // This is a register argument - possibly update it in the table fgArgTabEntryPtr entry = call->fgArgInfo->RemorphRegArg(argIndex, argx, args, nextRegNum, size, argAlign); if (entry->isNonStandard) { argIndex++; continue; } } // Setup the next argRegNum value if (!isBackFilled) { #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) if (isStructArg) { intArgRegNum += structIntRegs; fltArgRegNum += structFloatRegs; } else #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) { if (passUsingFloatRegs) { fltArgRegNum += size; #if defined(_TARGET_AMD64_) && !defined(UNIX_AMD64_ABI) argSkippedRegMask |= genMapArgNumToRegMask(intArgRegNum, TYP_I_IMPL); intArgRegNum = min(intArgRegNum + size, MAX_REG_ARG); #endif // _TARGET_AMD64_ #ifdef _TARGET_ARM_ if (fltArgRegNum > MAX_FLOAT_REG_ARG) { // This indicates a partial enregistration of a struct type assert(varTypeIsStruct(argx)); unsigned numRegsPartial = size - (fltArgRegNum - MAX_FLOAT_REG_ARG); assert((unsigned char)numRegsPartial == numRegsPartial); call->fgArgInfo->SplitArg(argIndex, numRegsPartial, size - numRegsPartial); fltArgRegNum = MAX_FLOAT_REG_ARG; } #endif // _TARGET_ARM_ } else { intArgRegNum += size; #if defined(_TARGET_AMD64_) && !defined(UNIX_AMD64_ABI) fltArgSkippedRegMask |= genMapArgNumToRegMask(fltArgRegNum, TYP_DOUBLE); fltArgRegNum = min(fltArgRegNum + size, MAX_FLOAT_REG_ARG); #endif // _TARGET_AMD64_ #ifdef _TARGET_ARM_ if (intArgRegNum > MAX_REG_ARG) { // This indicates a partial enregistration of a struct type assert((isStructArg) || argx->OperIsCopyBlkOp() || (argx->gtOper == GT_COMMA && (args->gtFlags & GTF_ASG))); unsigned numRegsPartial = size - (intArgRegNum - MAX_REG_ARG); assert((unsigned char)numRegsPartial == numRegsPartial); call->fgArgInfo->SplitArg(argIndex, numRegsPartial, size - numRegsPartial); intArgRegNum = MAX_REG_ARG; fgPtrArgCntCur += size - numRegsPartial; } #endif // _TARGET_ARM_ } } } } else // We have an argument that is not passed in a register { fgPtrArgCntCur += size; // If the register arguments have not been determined then we must fill in the argInfo if (!lateArgsComputed) { // This is a stack argument - put it in the table call->fgArgInfo->AddStkArg(argIndex, argx, args, size, argAlign FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(isStructArg)); } else { // This is a stack argument - possibly update it in the table call->fgArgInfo->RemorphStkArg(argIndex, argx, args, size, argAlign); } } if (copyBlkClass != NO_CLASS_HANDLE) { noway_assert(!lateArgsComputed); fgMakeOutgoingStructArgCopy(call, args, argIndex, copyBlkClass FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(&structDesc)); } #ifndef LEGACY_BACKEND if (argx->gtOper == GT_MKREFANY) { NYI_X86("MKREFANY"); // 'Lower' the MKREFANY tree and insert it. noway_assert(!lateArgsComputed); // Get a new temp // Here we don't need unsafe value cls check since the addr of temp is used only in mkrefany unsigned tmp = lvaGrabTemp(true DEBUGARG("by-value mkrefany struct argument")); lvaSetStruct(tmp, impGetRefAnyClass(), false); // Build the mkrefany as a comma node: // (tmp.ptr=argx),(tmp.type=handle) GenTreeLclFld* destPtrSlot = gtNewLclFldNode(tmp, TYP_I_IMPL, offsetof(CORINFO_RefAny, dataPtr)); GenTreeLclFld* destTypeSlot = gtNewLclFldNode(tmp, TYP_I_IMPL, offsetof(CORINFO_RefAny, type)); destPtrSlot->gtFieldSeq = GetFieldSeqStore()->CreateSingleton(GetRefanyDataField()); destPtrSlot->gtFlags |= GTF_VAR_DEF; destTypeSlot->gtFieldSeq = GetFieldSeqStore()->CreateSingleton(GetRefanyTypeField()); destTypeSlot->gtFlags |= GTF_VAR_DEF; GenTreePtr asgPtrSlot = gtNewAssignNode(destPtrSlot, argx->gtOp.gtOp1); GenTreePtr asgTypeSlot = gtNewAssignNode(destTypeSlot, argx->gtOp.gtOp2); GenTreePtr asg = gtNewOperNode(GT_COMMA, TYP_VOID, asgPtrSlot, asgTypeSlot); // Change the expression to "(tmp=val)" args->gtOp.gtOp1 = asg; // EvalArgsToTemps will cause tmp to actually get loaded as the argument call->fgArgInfo->EvalToTmp(argIndex, tmp, asg); lvaSetVarAddrExposed(tmp); } #endif // !LEGACY_BACKEND argIndex++; #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING if (nonRegPassableStruct) { nonRegPassedStructSlots += size; } else #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING { argSlots += size; } } // end foreach argument loop if (!lateArgsComputed) { call->fgArgInfo->ArgsComplete(); call->gtCallRegUsedMask = genIntAllRegArgMask(intArgRegNum) & ~argSkippedRegMask; if (fltArgRegNum > 0) { #if defined(_TARGET_ARM_) || defined(_TARGET_AMD64_) call->gtCallRegUsedMask |= genFltAllRegArgMask(fltArgRegNum) & ~fltArgSkippedRegMask; #endif } } if (call->gtCallArgs) { UpdateGT_LISTFlags(call->gtCallArgs); } /* Process the function address, if indirect call */ if (call->gtCallType == CT_INDIRECT) call->gtCallAddr = fgMorphTree(call->gtCallAddr); call->fgArgInfo->RecordStkLevel(fgPtrArgCntCur); if ((call->gtCallType == CT_INDIRECT) && (call->gtCallCookie != NULL)) fgPtrArgCntCur++; /* Remember the maximum value we ever see */ if (fgPtrArgCntMax < fgPtrArgCntCur) fgPtrArgCntMax = fgPtrArgCntCur; /* The call will pop all the arguments we pushed */ fgPtrArgCntCur = genPtrArgCntSav; #if FEATURE_FIXED_OUT_ARGS // Update the outgoing argument size. // If the call is a fast tail call, it will setup its arguments in incoming arg // area instead of the out-going arg area. Therefore, don't consider fast tail // calls to update lvaOutgoingArgSpaceSize. if (!call->IsFastTailCall()) { unsigned preallocatedArgCount; #if defined(_TARGET_ARMARCH_) // First slots go in registers only, no stack needed. // TODO-ARMArch-CQ: This calculation is only accurate for integer arguments, // and ignores floating point args (it is overly conservative in that case). if (argSlots <= MAX_REG_ARG) { preallocatedArgCount = 0; } else { preallocatedArgCount = argSlots - MAX_REG_ARG; } #elif defined(UNIX_AMD64_ABI) opts.compNeedToAlignFrame = true; // First slots go in registers only, no stack needed. // TODO-Amd64-Unix-CQ This calculation is only accurate for integer arguments, // and ignores floating point args (it is overly conservative in that case). if (argSlots <= MAX_REG_ARG) { preallocatedArgCount = nonRegPassedStructSlots; } else { preallocatedArgCount = argSlots + nonRegPassedStructSlots - MAX_REG_ARG; } #elif defined(_TARGET_AMD64_) preallocatedArgCount = max(4, argSlots); #else #error Unsupported or unset target architecture #endif // _TARGET_* if (preallocatedArgCount * REGSIZE_BYTES > lvaOutgoingArgSpaceSize) { lvaOutgoingArgSpaceSize = preallocatedArgCount * REGSIZE_BYTES; // If a function has localloc, we will need to move the outgoing arg space when the // localloc happens. When we do this, we need to maintain stack alignment. To avoid // leaving alignment-related holes when doing this move, make sure the outgoing // argument space size is a multiple of the stack alignment by aligning up to the next // stack alignment boundary. if (compLocallocUsed) { lvaOutgoingArgSpaceSize = (lvaOutgoingArgSpaceSize + (STACK_ALIGN - 1)) & ~(STACK_ALIGN - 1); } } } #endif // FEATURE_FIXED_OUT_ARGS /* Update the 'side effect' flags value for the call */ call->gtFlags |= (flagsSummary & GTF_ALL_EFFECT); // If the register arguments have already been determined // or we have no register arguments then we are done. bool needEvalArgsToTemps = true; if (lateArgsComputed || (intArgRegNum == 0 && fltArgRegNum == 0 && !hasNonStandardArg && !hasStructArgument)) { needEvalArgsToTemps = false; } if (needEvalArgsToTemps) { // This is the first time that we morph this call AND it has register arguments. // Follow into the code below and do the 'defer or eval to temp' analysis. call->fgArgInfo->SortArgs(); call->fgArgInfo->EvalArgsToTemps(); // We may have updated the arguments if (call->gtCallArgs) { UpdateGT_LISTFlags(call->gtCallArgs); } } #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING // Rewrite the struct args to be passed by value on stack or in registers. fgMorphSystemVStructArgs(call, hasStructArgument); #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING return call; } #ifdef _PREFAST_ #pragma warning(pop) #endif #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING // fgMorphSystemVStructArgs: // Rewrite the struct args to be passed by value on stack or in registers. // // args: // call: The call whose arguments need to be morphed. // hasStructArgument: Whether this call has struct arguments. // void Compiler::fgMorphSystemVStructArgs(GenTreeCall* call, bool hasStructArgument) { unsigned flagsSummary = 0; GenTreePtr args; GenTreePtr argx; if (hasStructArgument) { fgArgInfoPtr allArgInfo = call->fgArgInfo; for (args = call->gtCallArgs; args != nullptr; args = args->gtOp.gtOp2) { // For late arguments the arg tree that is overridden is in the gtCallLateArgs list. // For such late args the gtCallArgList contains the setup arg node (evaluating the arg.) // The tree from the gtCallLateArgs list is passed to the callee. The fgArgEntry node contains the mapping // between the nodes in both lists. If the arg is not a late arg, the fgArgEntry->node points to itself, // otherwise points to the list in the late args list. bool isLateArg = (args->gtOp.gtOp1->gtFlags & GTF_LATE_ARG) != 0; fgArgTabEntryPtr fgEntryPtr = gtArgEntryByNode(call, args->gtOp.gtOp1); assert(fgEntryPtr != nullptr); GenTreePtr argx = fgEntryPtr->node; GenTreePtr lateList = nullptr; GenTreePtr lateNode = nullptr; if (isLateArg) { for (GenTreePtr list = call->gtCallLateArgs; list; list = list->MoveNext()) { assert(list->IsList()); GenTreePtr argNode = list->Current(); if (argx == argNode) { lateList = list; lateNode = argNode; break; } } assert(lateList != nullptr && lateNode != nullptr); } GenTreePtr arg = argx; bool argListCreated = false; var_types type = arg->TypeGet(); if (varTypeIsStruct(type)) { var_types originalType = type; // If we have already processed the arg... if (arg->OperGet() == GT_LIST && varTypeIsStruct(arg)) { continue; } // If already OBJ it is set properly already. if (arg->OperGet() == GT_OBJ) { assert(!fgEntryPtr->structDesc.passedInRegisters); continue; } assert( arg->OperGet() == GT_LCL_VAR || arg->OperGet() == GT_LCL_FLD || (arg->OperGet() == GT_ADDR && (arg->gtOp.gtOp1->OperGet() == GT_LCL_FLD || arg->gtOp.gtOp1->OperGet() == GT_LCL_VAR))); GenTreeLclVarCommon* lclCommon = arg->OperGet() == GT_ADDR ? arg->gtOp.gtOp1->AsLclVarCommon() : arg->AsLclVarCommon(); if (fgEntryPtr->structDesc.passedInRegisters) { if (fgEntryPtr->structDesc.eightByteCount == 1) { // Change the type and below the code will change the LclVar to a LCL_FLD type = GetTypeFromClassificationAndSizes(fgEntryPtr->structDesc.eightByteClassifications[0], fgEntryPtr->structDesc.eightByteSizes[0]); } else if (fgEntryPtr->structDesc.eightByteCount == 2) { // Create LCL_FLD for each eightbyte. argListCreated = true; // Second eightbyte. GenTreeLclFld* newLclField = new(this, GT_LCL_FLD) GenTreeLclFld( GetTypeFromClassificationAndSizes( fgEntryPtr->structDesc.eightByteClassifications[1], fgEntryPtr->structDesc.eightByteSizes[1]), lclCommon->gtLclNum, fgEntryPtr->structDesc.eightByteOffsets[1]); GenTreeArgList* secondNode = gtNewListNode(newLclField, nullptr); secondNode->gtType = originalType; // Preserve the type. It is a special case. newLclField->gtFieldSeq = FieldSeqStore::NotAField(); // First field arg->AsLclFld()->gtFieldSeq = FieldSeqStore::NotAField(); arg->gtType = GetTypeFromClassificationAndSizes( fgEntryPtr->structDesc.eightByteClassifications[0], fgEntryPtr->structDesc.eightByteSizes[0]); arg = gtNewListNode(arg, secondNode); arg->gtType = type; // Preserve the type. It is a special case. } else { assert(false && "More than two eightbytes detected for CLR."); // No more than two eightbytes for the CLR. } } // If we didn't change the type of the struct, it means // its classification doesn't support to be passed directly through a // register, so we need to pass a pointer to the destination where // where we copied the struct to. if (!argListCreated) { if (fgEntryPtr->structDesc.passedInRegisters) { arg->gtType = type; } else { // Make sure this is an addr node. if (arg->OperGet() != GT_ADDR && arg->OperGet() != GT_LCL_VAR_ADDR) { arg = gtNewOperNode(GT_ADDR, TYP_I_IMPL, arg); } assert(arg->OperGet() == GT_ADDR || arg->OperGet() == GT_LCL_VAR_ADDR); // Create an Obj of the temp to use it as a call argument. arg = new (this, GT_OBJ) GenTreeObj(originalType, arg, lvaGetStruct(lclCommon->gtLclNum)); arg->gtFlags |= GTF_EXCEPT; flagsSummary |= GTF_EXCEPT; } } } if (argx != arg) { bool isLateArg = (args->gtOp.gtOp1->gtFlags & GTF_LATE_ARG) != 0; fgArgTabEntryPtr fgEntryPtr = gtArgEntryByNode(call, args->gtOp.gtOp1); assert(fgEntryPtr != nullptr); GenTreePtr argx = fgEntryPtr->node; GenTreePtr lateList = nullptr; GenTreePtr lateNode = nullptr; if (isLateArg) { for (GenTreePtr list = call->gtCallLateArgs; list; list = list->MoveNext()) { assert(list->IsList()); GenTreePtr argNode = list->Current(); if (argx == argNode) { lateList = list; lateNode = argNode; break; } } assert(lateList != nullptr && lateNode != nullptr); } fgEntryPtr->node = arg; if (isLateArg) { lateList->gtOp.gtOp1 = arg; } else { args->gtOp.gtOp1 = arg; } } } } // Update the flags call->gtFlags |= (flagsSummary & GTF_ALL_EFFECT); } #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING // Make a copy of a struct variable if necessary, to pass to a callee. // returns: tree that computes address of the outgoing arg void Compiler::fgMakeOutgoingStructArgCopy(GenTreeCall* call, GenTree* args, unsigned argIndex, CORINFO_CLASS_HANDLE copyBlkClass FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* const structDescPtr)) { GenTree* argx = args->Current(); noway_assert(argx->gtOper != GT_MKREFANY); // See if we need to insert a copy at all // Case 1: don't need a copy if it is the last use of a local. We can't determine that all of the time // but if there is only one use and no loops, the use must be last. if (argx->gtOper == GT_OBJ) { GenTree* lcl = argx->gtOp.gtOp1; if (lcl->OperIsLocal()) { unsigned varNum = lcl->AsLclVarCommon()->GetLclNum(); if (lvaIsImplicitByRefLocal(varNum)) { LclVarDsc* varDsc = &lvaTable[varNum]; if (varDsc->lvRefCnt == 1 && !fgMightHaveLoop()) { varDsc->lvRefCnt = 0; args->gtOp.gtOp1 = lcl; fgArgTabEntryPtr fp = Compiler::gtArgEntryByNode(call, argx); fp->node = lcl; JITDUMP("did not have to make outgoing copy for V%2d", varNum); varDsc->lvRefCnt = 0; return; } else { varDsc->lvRefCnt = 0; } } } } if (fgOutgoingArgTemps == nullptr) fgOutgoingArgTemps = hashBv::Create(this); unsigned tmp = 0; bool found = false; // Attempt to find a local we have already used for an outgoing struct and reuse it. // We do not reuse within a statement. if (!opts.MinOpts()) { indexType lclNum; FOREACH_HBV_BIT_SET(lclNum, fgOutgoingArgTemps) { LclVarDsc* varDsc = &lvaTable[lclNum]; if (typeInfo::AreEquivalent(varDsc->lvVerTypeInfo, typeInfo(TI_STRUCT, copyBlkClass)) && !fgCurrentlyInUseArgTemps->testBit(lclNum)) { tmp = (unsigned) lclNum; found = true; JITDUMP("reusing outgoing struct arg"); break; } } NEXT_HBV_BIT_SET; } // Create the CopyBlk tree and insert it. if (!found) { // Get a new temp // Here We don't need unsafe value cls check, since the addr of this temp is used only in copyblk. tmp = lvaGrabTemp(true DEBUGARG("by-value struct argument")); lvaSetStruct(tmp, copyBlkClass, false); fgOutgoingArgTemps->setBit(tmp); } fgCurrentlyInUseArgTemps->setBit(tmp); // TYP_SIMD structs should not be enregistered, since ABI requires it to be // allocated on stack and address of it needs to be passed. if (lclVarIsSIMDType(tmp)) { lvaSetVarDoNotEnregister(tmp DEBUG_ARG(DNER_IsStruct)); } // Create a reference to the temp GenTreePtr dest = gtNewLclvNode(tmp, lvaTable[tmp].lvType); dest->gtFlags |= (GTF_DONT_CSE | GTF_VAR_DEF); // This is a def of the local, "entire" by construction. dest = gtNewOperNode(GT_ADDR, TYP_BYREF, dest); lvaTable[tmp].incRefCnts(compCurBB->getBBWeight(this), this); GenTreePtr src; if (argx->gtOper == GT_OBJ) { src = argx->gtOp.gtOp1; } else { argx->gtFlags |= GTF_DONT_CSE; src = gtNewOperNode(GT_ADDR, TYP_BYREF, argx); } // Copy the valuetype to the temp GenTreePtr copyBlk = gtNewCpObjNode(dest, src, copyBlkClass, false); copyBlk = fgMorphCopyBlock(copyBlk); #if FEATURE_FIXED_OUT_ARGS // Do the copy early, and evalute the temp later (see EvalArgsToTemps) // When on Unix create LCL_FLD for structs passed in more than one registers. See fgMakeTmpArgNode GenTreePtr arg = copyBlk; #else // FEATURE_FIXED_OUT_ARGS // Structs are always on the stack, and thus never need temps // so we have to put the copy and temp all into one expression GenTreePtr arg = fgMakeTmpArgNode( tmp FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(structDescPtr->passedInRegisters)); // Change the expression to "(tmp=val),tmp" arg = gtNewOperNode(GT_COMMA, arg->TypeGet(), copyBlk, arg); #endif // FEATURE_FIXED_OUT_ARGS args->gtOp.gtOp1 = arg; call->fgArgInfo->EvalToTmp(argIndex, tmp, arg); return; } #ifdef _TARGET_ARM_ // See declaration for specification comment. void Compiler::fgAddSkippedRegsInPromotedStructArg(LclVarDsc* varDsc, unsigned firstArgRegNum, regMaskTP* pArgSkippedRegMask) { assert(varDsc->lvPromoted); // There's no way to do these calculations without breaking abstraction and assuming that // integer register arguments are consecutive ints. They are on ARM. // To start, figure out what register contains the last byte of the first argument. LclVarDsc* firstFldVarDsc = &lvaTable[varDsc->lvFieldLclStart]; unsigned lastFldRegOfLastByte = (firstFldVarDsc->lvFldOffset + firstFldVarDsc->lvExactSize - 1) / TARGET_POINTER_SIZE;; // Now we're keeping track of the register that the last field ended in; see what registers // subsequent fields start in, and whether any are skipped. // (We assume here the invariant that the fields are sorted in offset order.) for (unsigned fldVarOffset = 1; fldVarOffset < varDsc->lvFieldCnt; fldVarOffset++) { unsigned fldVarNum = varDsc->lvFieldLclStart + fldVarOffset; LclVarDsc* fldVarDsc = &lvaTable[fldVarNum]; unsigned fldRegOffset = fldVarDsc->lvFldOffset / TARGET_POINTER_SIZE; assert(fldRegOffset >= lastFldRegOfLastByte); // Assuming sorted fields. // This loop should enumerate the offsets of any registers skipped. // Find what reg contains the last byte: // And start at the first register after that. If that isn't the first reg of the current for (unsigned skippedRegOffsets = lastFldRegOfLastByte + 1; skippedRegOffsets < fldRegOffset; skippedRegOffsets++) { // If the register number would not be an arg reg, we're done. if (firstArgRegNum + skippedRegOffsets >= MAX_REG_ARG) return; *pArgSkippedRegMask |= genRegMask(regNumber(firstArgRegNum + skippedRegOffsets)); } lastFldRegOfLastByte = (fldVarDsc->lvFldOffset + fldVarDsc->lvExactSize - 1) / TARGET_POINTER_SIZE; } } #endif // _TARGET_ARM_ /***************************************************************************** * * The companion to impFixupStructReturn. Now that the importer is done * and we no longer care as much about the declared return type, change to * precomputed native return type (at least for architectures that don't * always use return buffers for structs). * */ void Compiler::fgFixupStructReturn(GenTreePtr call) { bool callHasRetBuffArg = ((call->gtCall.gtCallMoreFlags & GTF_CALL_M_RETBUFFARG) != 0); #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR structDesc; if (!callHasRetBuffArg && varTypeIsStruct(call) && call->gtCall.gtRetClsHnd != NO_CLASS_HANDLE) { eeGetSystemVAmd64PassStructInRegisterDescriptor(gtGetStructHandleIfPresent(call), &structDesc); } #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) if (!callHasRetBuffArg && (varTypeIsStruct(call))) { #if defined(_TARGET_ARM_) if (call->gtCall.IsVarargs() || !IsHfa(call)) #elif defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) if (!structDesc.passedInRegisters) #endif // !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) { // Now that we are past the importer, re-type this node so the register predictor does // the right thing call->gtType = genActualType((var_types)call->gtCall.gtReturnType); } #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) else { if (structDesc.passedInRegisters && structDesc.eightByteCount <= 1) { call->gtType = genActualType(getEightByteType(structDesc, 0)); } } #endif // !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) } #ifdef _TARGET_ARM_ // Either we don't have a struct now or if struct, then it is HFA returned in regs. assert(!varTypeIsStruct(call) || (IsHfa(call) && !callHasRetBuffArg)); #else #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) // Either we don't have a struct now or if struct, then it is a struct returned in regs or in return buffer. assert(!varTypeIsStruct(call) || (structDesc.passedInRegisters) || (callHasRetBuffArg)); #else // !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) // No more struct returns assert(call->TypeGet() != TYP_STRUCT); #endif // !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) #endif #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) // If there is a struct that is returned in registers there might be a retbuf (homing space for the return) and type struct. assert(!callHasRetBuffArg || (call->TypeGet() == TYP_VOID) || varTypeIsStruct(call)); #else // !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) // If it was a struct return, it has been transformed into a call // with a return buffer (that returns TYP_VOID) or into a return // of a primitive/enregisterable type assert(!callHasRetBuffArg || (call->TypeGet() == TYP_VOID)); #endif // !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) } /***************************************************************************** * * A little helper used to rearrange nested commutative operations. The * effect is that nested associative, commutative operations are transformed * into a 'left-deep' tree, i.e. into something like this: * * (((a op b) op c) op d) op... */ #if REARRANGE_ADDS void Compiler::fgMoveOpsLeft(GenTreePtr tree) { GenTreePtr op1; GenTreePtr op2; genTreeOps oper; do { op1 = tree->gtOp.gtOp1; op2 = tree->gtOp.gtOp2; oper = tree->OperGet(); noway_assert(GenTree::OperIsCommutative(oper)); noway_assert(oper == GT_ADD || oper == GT_XOR || oper == GT_OR || oper == GT_AND || oper == GT_MUL); noway_assert(!varTypeIsFloating(tree->TypeGet()) || !opts.genFPorder); noway_assert(oper == op2->gtOper); // Commutativity doesn't hold if overflow checks are needed if (tree->gtOverflowEx() || op2->gtOverflowEx()) return; if (gtIsActiveCSE_Candidate(op2)) { // If we have marked op2 as a CSE candidate, // we can't perform a commutative reordering // because any value numbers that we computed for op2 // will be incorrect after performing a commutative reordering // return; } if (oper == GT_MUL && (op2->gtFlags & GTF_MUL_64RSLT)) return; // Check for GTF_ADDRMODE_NO_CSE flag on add/mul Binary Operators if ( ((oper == GT_ADD) || (oper == GT_MUL)) && ((tree->gtFlags & GTF_ADDRMODE_NO_CSE) != 0) ) { return; } if ( (tree->gtFlags | op2->gtFlags) & GTF_BOOLEAN ) { // We could deal with this, but we were always broken and just hit the assert // below regarding flags, which means it's not frequent, so will just bail out. // See #195514 return; } noway_assert(!tree->gtOverflowEx() && !op2->gtOverflowEx()); GenTreePtr ad1 = op2->gtOp.gtOp1; GenTreePtr ad2 = op2->gtOp.gtOp2; // Compiler::optOptimizeBools() can create GT_OR of two GC pointers yeilding a GT_INT // We can not reorder such GT_OR trees // if (varTypeIsGC(ad1->TypeGet()) != varTypeIsGC(op2->TypeGet())) break; /* Change "(x op (y op z))" to "(x op y) op z" */ /* ie. "(op1 op (ad1 op ad2))" to "(op1 op ad1) op ad2" */ GenTreePtr new_op1 = op2; new_op1->gtOp.gtOp1 = op1; new_op1->gtOp.gtOp2 = ad1; /* Change the flags. */ // Make sure we arent throwing away any flags noway_assert((new_op1->gtFlags & ~( GTF_MAKE_CSE | GTF_DONT_CSE | // It is ok that new_op1->gtFlags contains GTF_DONT_CSE flag. GTF_REVERSE_OPS | // The reverse ops flag also can be set, it will be re-calculated GTF_NODE_MASK|GTF_ALL_EFFECT|GTF_UNSIGNED)) == 0); new_op1->gtFlags = (new_op1->gtFlags & (GTF_NODE_MASK | GTF_DONT_CSE)) | // Make sure we propagate GTF_DONT_CSE flag. (op1->gtFlags & GTF_ALL_EFFECT) | (ad1->gtFlags & GTF_ALL_EFFECT); /* Retype new_op1 if it has not/become a GC ptr. */ if (varTypeIsGC(op1->TypeGet())) { noway_assert((varTypeIsGC(tree->TypeGet()) && op2->TypeGet() == TYP_I_IMPL && oper == GT_ADD) || // byref(ref + (int+int)) (varTypeIsI (tree->TypeGet()) && op2->TypeGet() == TYP_I_IMPL && oper == GT_OR)); // int(gcref | int(gcref|intval)) new_op1->gtType = tree->gtType; } else if (varTypeIsGC(ad2->TypeGet())) { // Neither ad1 nor op1 are GC. So new_op1 isnt either noway_assert(op1->gtType == TYP_I_IMPL && ad1->gtType == TYP_I_IMPL); new_op1->gtType = TYP_I_IMPL; } // If new_op1 is a new expression. Assign it a new unique value number. // vnStore is null before the ValueNumber phase has run if (vnStore != nullptr) { // We can only keep the old value number on new_op1 if both op1 and ad2 // have the same non-NoVN value numbers. Since op is commutative, comparing // only ad2 and op1 is enough. if ((op1->gtVNPair.GetLiberal() == ValueNumStore::NoVN) || (ad2->gtVNPair.GetLiberal() == ValueNumStore::NoVN) || (ad2->gtVNPair.GetLiberal() != op1->gtVNPair.GetLiberal())) { new_op1->gtVNPair.SetBoth(vnStore->VNForExpr(new_op1->TypeGet())); } } tree->gtOp.gtOp1 = new_op1; tree->gtOp.gtOp2 = ad2; /* If 'new_op1' is now the same nested op, process it recursively */ if ((ad1->gtOper == oper) && !ad1->gtOverflowEx()) fgMoveOpsLeft(new_op1); /* If 'ad2' is now the same nested op, process it * Instead of recursion, we set up op1 and op2 for the next loop. */ op1 = new_op1; op2 = ad2; } while ((op2->gtOper == oper) && !op2->gtOverflowEx()); return; } #endif /*****************************************************************************/ void Compiler::fgSetRngChkTarget(GenTreePtr tree, bool delay) { GenTreeBoundsChk* bndsChk = nullptr; SpecialCodeKind kind = SCK_RNGCHK_FAIL; #ifdef FEATURE_SIMD if ((tree->gtOper == GT_ARR_BOUNDS_CHECK) || (tree->gtOper == GT_SIMD_CHK)) #else // FEATURE_SIMD if (tree->gtOper == GT_ARR_BOUNDS_CHECK) #endif // FEATURE_SIMD { bndsChk = tree->AsBoundsChk(); kind = tree->gtBoundsChk.gtThrowKind; } else { noway_assert((tree->gtOper == GT_ARR_ELEM) || (tree->gtOper == GT_ARR_INDEX)); } #ifdef _TARGET_X86_ unsigned callStkDepth = fgPtrArgCntCur; #else // only x86 pushes args const unsigned callStkDepth = 0; #endif if (opts.MinOpts()) { delay = false; // we need to initialize this field if (fgGlobalMorph && bndsChk != nullptr) { bndsChk->gtStkDepth = callStkDepth; } } if (!opts.compDbgCode) { if (delay || compIsForInlining()) { /* We delay this until after loop-oriented range check analysis. For now we merely store the current stack level in the tree node. */ if (bndsChk != nullptr) { noway_assert(!bndsChk->gtIndRngFailBB || previousCompletedPhase >= PHASE_OPTIMIZE_LOOPS); bndsChk->gtStkDepth = callStkDepth; } } else { /* Create/find the appropriate "range-fail" label */ // fgPtrArgCntCur is only valid for global morph or if we walk full stmt. noway_assert((bndsChk != nullptr) || fgGlobalMorph); unsigned stkDepth = (bndsChk != nullptr) ? bndsChk->gtStkDepth : callStkDepth; BasicBlock * rngErrBlk = fgRngChkTarget(compCurBB, stkDepth, kind); /* Add the label to the indirection node */ if (bndsChk != nullptr) { bndsChk->gtIndRngFailBB = gtNewCodeRef(rngErrBlk); } } } } /***************************************************************************** * * Expand a GT_INDEX node and fully morph the child operands * * The orginal GT_INDEX node is bashed into the GT_IND node that accesses * the array element. We expand the GT_INDEX node into a larger tree that * evaluates the array base and index. The simplest expansion is a GT_COMMA * with a GT_ARR_BOUND_CHK and a GT_IND with a GTF_INX_RNGCHK flag. * For complex array or index expressions one or more GT_COMMA assignments * are inserted so that we only evaluate the array or index expressions once. * * The fully expanded tree is then morphed. This causes gtFoldExpr to * perform local constant prop and reorder the constants in the tree and * fold them. * * We then parse the resulting array element expression in order to locate * and label the constants and variables that occur in the tree. */ const int MAX_ARR_COMPLEXITY = 4; const int MAX_INDEX_COMPLEXITY = 4; GenTreePtr Compiler::fgMorphArrayIndex(GenTreePtr tree) { noway_assert(tree->gtOper == GT_INDEX); GenTreeIndex* asIndex = tree->AsIndex(); var_types elemTyp = tree->TypeGet(); unsigned elemSize = tree->gtIndex.gtIndElemSize; CORINFO_CLASS_HANDLE elemStructType = tree->gtIndex.gtStructElemClass; noway_assert(elemTyp != TYP_STRUCT || elemStructType != nullptr); #ifdef FEATURE_SIMD if (featureSIMD && varTypeIsStruct(elemTyp) && elemSize <= getSIMDVectorRegisterByteLength()) { // If this is a SIMD type, this is the point at which we lose the type information, // so we need to set the correct type on the GT_IND. // (We don't care about the base type here, so we only check, but don't retain, the return value). unsigned simdElemSize = 0; if (getBaseTypeAndSizeOfSIMDType(elemStructType, &simdElemSize) != TYP_UNKNOWN) { assert(simdElemSize == elemSize); elemTyp = getSIMDTypeForSize(elemSize); // This is the new type of the node. tree->gtType = elemTyp; // Now set elemStructType to null so that we don't confuse value numbering. elemStructType = nullptr; } } #endif // FEATURE_SIMD GenTreePtr arrRef = asIndex->Arr(); GenTreePtr index = asIndex->Index(); // Set up the the array length's offset into lenOffs // And the the first element's offset into elemOffs ssize_t lenOffs; ssize_t elemOffs; if (tree->gtFlags & GTF_INX_STRING_LAYOUT) { lenOffs = offsetof(CORINFO_String, stringLen); elemOffs = offsetof(CORINFO_String, chars); tree->gtFlags &= ~GTF_INX_STRING_LAYOUT; // Clear this flag as it is used for GTF_IND_VOLATILE } else if (tree->gtFlags & GTF_INX_REFARR_LAYOUT) { lenOffs = offsetof(CORINFO_RefArray, length); elemOffs = eeGetEEInfo()->offsetOfObjArrayData; } else // We have a standard array { lenOffs = offsetof(CORINFO_Array, length); elemOffs = offsetof(CORINFO_Array, u1Elems); } bool chkd = ((tree->gtFlags & GTF_INX_RNGCHK) != 0); // if false, range checking will be disabled bool nCSE = ((tree->gtFlags & GTF_DONT_CSE ) != 0); GenTreePtr arrRefDefn = nullptr; // non-NULL if we need to allocate a temp for the arrRef expression GenTreePtr indexDefn = nullptr; // non-NULL if we need to allocate a temp for the index expression GenTreePtr bndsChk = nullptr; // If we're doing range checking, introduce a GT_ARR_BOUNDS_CHECK node for the address. if (chkd) { GenTreePtr arrRef2 = nullptr; // The second copy will be used in array address expression GenTreePtr index2 = nullptr; // If the arrRef expression involves an assignment, a call or reads from global memory, // then we *must* allocate a temporary in which to "localize" those values, // to ensure that the same values are used in the bounds check and the actual // dereference. // Also we allocate the temporary when the arrRef is sufficiently complex/expensive. // if ((arrRef->gtFlags & (GTF_ASG|GTF_CALL|GTF_GLOB_REF)) || gtComplexityExceeds(&arrRef, MAX_ARR_COMPLEXITY)) { unsigned arrRefTmpNum = lvaGrabTemp(true DEBUGARG("arr expr")); arrRefDefn = gtNewTempAssign(arrRefTmpNum, arrRef); arrRef = gtNewLclvNode(arrRefTmpNum, arrRef->TypeGet()); arrRef2 = gtNewLclvNode(arrRefTmpNum, arrRef->TypeGet()); } else { arrRef2 = gtCloneExpr(arrRef); noway_assert(arrRef2 != nullptr); } // If the index expression involves an assignment, a call or reads from global memory, // we *must* allocate a temporary in which to "localize" those values, // to ensure that the same values are used in the bounds check and the actual // dereference. // Also we allocate the temporary when the index is sufficiently complex/expensive. // if ((index->gtFlags & (GTF_ASG|GTF_CALL|GTF_GLOB_REF)) || gtComplexityExceeds(&index, MAX_ARR_COMPLEXITY)) { unsigned indexTmpNum = lvaGrabTemp(true DEBUGARG("arr expr")); indexDefn = gtNewTempAssign(indexTmpNum, index); index = gtNewLclvNode(indexTmpNum, index->TypeGet()); index2 = gtNewLclvNode(indexTmpNum, index->TypeGet()); } else { index2 = gtCloneExpr(index); noway_assert(index2 != nullptr); } // Next introduce a GT_ARR_BOUNDS_CHECK node var_types bndsChkType = TYP_INT; // By default, try to use 32-bit comparison for array bounds check. #ifdef _TARGET_64BIT_ // The CLI Spec allows an array to be indexed by either an int32 or a native int. In the case // of a 64 bit architecture this means the array index can potentially be a TYP_LONG, so for this case, // the comparison will have to be widen to 64 bits. if (index->TypeGet() == TYP_I_IMPL) { bndsChkType = TYP_I_IMPL; } #endif // _TARGET_64BIT_ GenTree* arrLen = new (this, GT_ARR_LENGTH) GenTreeArrLen(TYP_INT, arrRef, (int)lenOffs); if (bndsChkType != TYP_INT) { arrLen = gtNewCastNode(bndsChkType, arrLen, bndsChkType); } GenTreeBoundsChk* arrBndsChk = new (this, GT_ARR_BOUNDS_CHECK) GenTreeBoundsChk(GT_ARR_BOUNDS_CHECK, TYP_VOID, arrLen, index, SCK_RNGCHK_FAIL); bndsChk = arrBndsChk; // Make sure to increment ref-counts if already ref-counted. if (lvaLocalVarRefCounted) { lvaRecursiveIncRefCounts(index); lvaRecursiveIncRefCounts(arrRef); } // Now we'll switch to using the second copies for arrRef and index // to compute the address expression arrRef = arrRef2; index = index2; } // Create the "addr" which is "*(arrRef + ((index * elemSize) + elemOffs))" GenTreePtr addr; // Widen 'index' on 64-bit targets #ifdef _TARGET_64BIT_ if (index->TypeGet() != TYP_I_IMPL) { if (index->OperGet() == GT_CNS_INT) { index->gtType = TYP_I_IMPL; } else { index = gtNewCastNode(TYP_I_IMPL, index, TYP_I_IMPL); } } #endif // _TARGET_64BIT_ /* Scale the index value if necessary */ if (elemSize > 1) { GenTreePtr size = gtNewIconNode(elemSize, TYP_I_IMPL); // Fix 392756 WP7 Crossgen // // During codegen optGetArrayRefScaleAndIndex() makes the assumption that op2 of a GT_MUL node // is a constant and is not capable of handling CSE'ing the elemSize constant into a lclvar. // Hence to prevent the constant from becoming a CSE we mark it as NO_CSE. // size->gtFlags |= GTF_DONT_CSE; /* Multiply by the array element size */ addr = gtNewOperNode(GT_MUL, TYP_I_IMPL, index, size); } else { addr = index; } /* Add the object ref to the element's offset */ addr = gtNewOperNode(GT_ADD, TYP_BYREF, arrRef, addr); /* Add the first element's offset */ GenTreePtr cns = gtNewIconNode(elemOffs, TYP_I_IMPL); addr = gtNewOperNode(GT_ADD, TYP_BYREF, addr, cns); #if SMALL_TREE_NODES assert(tree->gtFlags & GTF_NODE_LARGE); #endif // Change the orginal GT_INDEX node into a GT_IND node tree->SetOper(GT_IND); // If the index node is a floating-point type, notify the compiler // we'll potentially use floating point registers at the time of codegen. if (varTypeIsFloating(tree->gtType)) { this->compFloatingPointUsed = true; } // We've now consumed the GTF_INX_RNGCHK, and the node // is no longer a GT_INDEX node. tree->gtFlags &= ~GTF_INX_RNGCHK; tree->gtOp.gtOp1 = addr; // This is an array index expression. tree->gtFlags |= GTF_IND_ARR_INDEX; /* An indirection will cause a GPF if the address is null */ tree->gtFlags |= GTF_EXCEPT; if (nCSE) tree->gtFlags |= GTF_DONT_CSE; // Store information about it. GetArrayInfoMap()->Set(tree, ArrayInfo(elemTyp, elemSize, (int) elemOffs, elemStructType)); // Remember this 'indTree' that we just created, as we still need to attach the fieldSeq information to it. GenTreePtr indTree = tree; // Did we create a bndsChk tree? if (bndsChk) { // Use a GT_COMMA node to prepend the array bound check // tree = gtNewOperNode(GT_COMMA, elemTyp, bndsChk, tree); /* Mark the indirection node as needing a range check */ fgSetRngChkTarget(bndsChk); } if (indexDefn != nullptr) { // Use a GT_COMMA node to prepend the index assignment // tree = gtNewOperNode(GT_COMMA, tree->TypeGet(), indexDefn, tree); } if (arrRefDefn != nullptr) { // Use a GT_COMMA node to prepend the arRef assignment // tree = gtNewOperNode(GT_COMMA, tree->TypeGet(), arrRefDefn, tree); } // Currently we morph the tree to perform some folding operations prior // to attaching fieldSeq info and labeling constant array index contributions // fgMorphTree(tree); // Ideally we just want to proceed to attaching fieldSeq info and labeling the // constant array index contributions, but the morphing operation may have changed // the 'tree' into something that now unconditionally throws an exception. // // In such case the gtEffectiveVal could be a new tree or it's gtOper could be modified // or it could be left unchanged. If it is unchanged then we should not return, // instead we should proceed to attaching fieldSeq info, etc... // GenTreePtr arrElem = tree->gtEffectiveVal(); if (fgIsCommaThrow(tree)) { if ((arrElem != indTree) || // A new tree node may have been created (indTree->OperGet() != GT_IND)) // The GT_IND may have been changed to a GT_CNS_INT { return tree; // Just return the Comma-Throw, don't try to attach the fieldSeq info, etc.. } } assert(!fgGlobalMorph || (arrElem->gtFlags & GTF_MORPHED)); addr = arrElem->gtOp.gtOp1; assert(addr->TypeGet() == TYP_BYREF); GenTreePtr cnsOff = nullptr; if (addr->OperGet() == GT_ADD) { if (addr->gtOp.gtOp2->gtOper == GT_CNS_INT) { cnsOff = addr->gtOp.gtOp2; addr = addr->gtOp.gtOp1; } while ((addr->OperGet() == GT_ADD) || (addr->OperGet() == GT_SUB)) { assert(addr->TypeGet() == TYP_BYREF); GenTreePtr index = addr->gtOp.gtOp2; // Label any constant array index contributions with #ConstantIndex and any LclVars with GTF_VAR_ARR_INDEX index->LabelIndex(this); addr = addr->gtOp.gtOp1; } assert(addr->TypeGet() == TYP_REF); } else if (addr->OperGet() == GT_CNS_INT) { cnsOff = addr; } FieldSeqNode* firstElemFseq = GetFieldSeqStore()->CreateSingleton(FieldSeqStore::FirstElemPseudoField); if ((cnsOff != nullptr) && (cnsOff->gtIntCon.gtIconVal == elemOffs)) { // Assign it the [#FirstElem] field sequence // cnsOff->gtIntCon.gtFieldSeq = firstElemFseq; } else // We have folded the first element's offset with the index expression { // Build the [#ConstantIndex, #FirstElem] field sequence // FieldSeqNode* constantIndexFseq = GetFieldSeqStore()->CreateSingleton(FieldSeqStore::ConstantIndexPseudoField); FieldSeqNode* fieldSeq = GetFieldSeqStore()->Append(constantIndexFseq, firstElemFseq); if (cnsOff == nullptr) // It must have folded into a zero offset { // Record in the general zero-offset map. GetZeroOffsetFieldMap()->Set(addr, fieldSeq); } else { cnsOff->gtIntCon.gtFieldSeq = fieldSeq; } } return tree; } #ifdef _TARGET_X86_ /***************************************************************************** * * Wrap fixed stack arguments for varargs functions to go through varargs * cookie to access them, except for the cookie itself. * * Non-x86 platforms are allowed to access all arguments directly * so we don't need this code. * */ GenTreePtr Compiler::fgMorphStackArgForVarArgs(unsigned lclNum, var_types varType, unsigned lclOffs) { /* For the fixed stack arguments of a varargs function, we need to go through the varargs cookies to access them, except for the cookie itself */ LclVarDsc * varDsc = &lvaTable[lclNum]; if (varDsc->lvIsParam && !varDsc->lvIsRegArg && lclNum != lvaVarargsHandleArg) { // Create a node representing the local pointing to the base of the args GenTreePtr ptrArg = gtNewOperNode(GT_SUB, TYP_I_IMPL, gtNewLclvNode(lvaVarargsBaseOfStkArgs, TYP_I_IMPL), gtNewIconNode(varDsc->lvStkOffs - codeGen->intRegState.rsCalleeRegArgNum*sizeof(void*) + lclOffs)); // Access the argument through the local GenTreePtr tree = gtNewOperNode(GT_IND, varType, ptrArg); tree->gtFlags |= GTF_IND_TGTANYWHERE; if (varDsc->lvAddrExposed) { tree->gtFlags |= GTF_GLOB_REF; } return fgMorphTree(tree); } return NULL; } #endif /***************************************************************************** * * Transform the given GT_LCL_VAR tree for code generation. */ GenTreePtr Compiler::fgMorphLocalVar(GenTreePtr tree) { noway_assert(tree->gtOper == GT_LCL_VAR); unsigned lclNum = tree->gtLclVarCommon.gtLclNum; var_types varType = lvaGetRealType(lclNum); LclVarDsc * varDsc = &lvaTable[lclNum]; if (varDsc->lvAddrExposed) { tree->gtFlags |= GTF_GLOB_REF; } #ifdef _TARGET_X86_ if (info.compIsVarArgs) { GenTreePtr newTree = fgMorphStackArgForVarArgs(lclNum, varType, 0); if (newTree != NULL) return newTree; } #endif // _TARGET_X86_ /* If not during the global morphing phase bail */ if (!fgGlobalMorph) return tree; bool varAddr = (tree->gtFlags & GTF_DONT_CSE) != 0; noway_assert(!(tree->gtFlags & GTF_VAR_DEF) || varAddr); // GTF_VAR_DEF should always imply varAddr if (!varAddr && varTypeIsSmall(varDsc->TypeGet()) && varDsc->lvNormalizeOnLoad()) { #if LOCAL_ASSERTION_PROP /* Assertion prop can tell us to omit adding a cast here */ if (optLocalAssertionProp && optAssertionIsSubrange(tree, varType, apFull) != NO_ASSERTION_INDEX) { return tree; } #endif /* Small-typed arguments and aliased locals are normalized on load. Other small-typed locals are normalized on store. Also, under the debugger as the debugger could write to the variable. If this is one of the former, insert a narrowing cast on the load. ie. Convert: var-short --> cast-short(var-int) */ tree->gtType = TYP_INT; fgMorphTreeDone(tree); tree = gtNewCastNode(TYP_INT, tree, varType); fgMorphTreeDone(tree); return tree; } return tree; } /***************************************************************************** Grab a temp for big offset morphing. This method will grab a new temp if no temp of this "type" has been created. Or it will return the same cached one if it has been created. */ unsigned Compiler::fgGetBigOffsetMorphingTemp(var_types type) { unsigned lclNum = fgBigOffsetMorphingTemps[type]; if (lclNum == BAD_VAR_NUM) { // We haven't created a temp for this kind of type. Create one now. lclNum = lvaGrabTemp(false DEBUGARG("Big Offset Morphing")); fgBigOffsetMorphingTemps[type] = lclNum; } else { // We better get the right type. noway_assert(lvaTable[lclNum].TypeGet() == type); } noway_assert(lclNum != BAD_VAR_NUM); return lclNum; } /***************************************************************************** * * Transform the given GT_FIELD tree for code generation. */ GenTreePtr Compiler::fgMorphField(GenTreePtr tree, MorphAddrContext* mac) { assert(tree->gtOper == GT_FIELD); noway_assert(tree->gtFlags & GTF_GLOB_REF); CORINFO_FIELD_HANDLE symHnd = tree->gtField.gtFldHnd; unsigned fldOffset = tree->gtField.gtFldOffset; GenTreePtr objRef = tree->gtField.gtFldObj; bool fieldMayOverlap = false; if (tree->gtField.gtFldMayOverlap) { fieldMayOverlap = true; // Reset the flag because we may reuse the node. tree->gtField.gtFldMayOverlap = false; } #ifdef FEATURE_SIMD // if this field belongs to simd struct, tranlate it to simd instrinsic. if (mac == nullptr || mac->m_kind != MACK_Addr) { GenTreePtr newTree = fgMorphFieldToSIMDIntrinsicGet(tree); if (newTree != tree) { newTree = fgMorphSmpOp(newTree); return newTree; } } else if (objRef != nullptr && objRef->OperGet() == GT_ADDR && objRef->OperIsSIMD()) { // We have a field of an SIMD intrinsic in an address-taken context. // We need to copy the SIMD result to a temp, and take the field of that. GenTree* copy = fgCopySIMDNode(objRef->gtOp.gtOp1->AsSIMD()); objRef->gtOp.gtOp1 = copy; } #endif /* Is this an instance data member? */ if (objRef) { GenTreePtr addr; if (tree->gtFlags & GTF_IND_TLS_REF) NO_WAY("instance field can not be a TLS ref."); /* We'll create the expression "*(objRef + mem_offs)" */ noway_assert(varTypeIsGC(objRef->TypeGet()) || objRef->TypeGet() == TYP_I_IMPL); // An optimization for Contextful classes: // we unwrap the proxy when we have a 'this reference' if (info.compIsContextful && info.compUnwrapContextful && impIsThis(objRef)) { objRef = fgUnwrapProxy(objRef); } /* Now we have a tree like this: +--------------------+ | GT_FIELD | tree +----------+---------+ | +--------------+-------------+ | tree->gtField.gtFldObj | +--------------+-------------+ We want to make it like this (when fldOffset is <= MAX_UNCHECKED_OFFSET_FOR_NULL_OBJECT): +--------------------+ | GT_IND/GT_OBJ | tree +---------+----------+ | | +---------+----------+ | GT_ADD | addr +---------+----------+ | / \ / \ / \ +-------------------+ +----------------------+ | objRef | | fldOffset | | | | (when fldOffset !=0) | +-------------------+ +----------------------+ or this (when fldOffset is > MAX_UNCHECKED_OFFSET_FOR_NULL_OBJECT): +--------------------+ | GT_IND/GT_OBJ | tree +----------+---------+ | +----------+---------+ | GT_COMMA | comma2 +----------+---------+ | / \ / \ / \ / \ +---------+----------+ +---------+----------+ comma | GT_COMMA | | "+" (i.e. GT_ADD) | addr +---------+----------+ +---------+----------+ | | / \ / \ / \ / \ / \ / \ +-----+-----+ +-----+-----+ +---------+ +-----------+ asg | GT_ASG | ind | GT_IND | | tmpLcl | | fldOffset | +-----+-----+ +-----+-----+ +---------+ +-----------+ | | / \ | / \ | / \ | +-----+-----+ +-----+-----+ +-----------+ | tmpLcl | | objRef | | tmpLcl | +-----------+ +-----------+ +-----------+ */ var_types objRefType = objRef->TypeGet(); GenTreePtr comma = NULL; bool addedExplicitNullCheck = false; // NULL mac means we encounter the GT_FIELD first. This denotes a dereference of the field, // and thus is equivalent to a MACK_Ind with zero offset. MorphAddrContext defMAC(MACK_Ind); if (mac == NULL) mac = &defMAC; // This flag is set to enable the "conservative" style of explicit null-check insertion. // This means that we insert an explicit null check whenever we create byref by adding a // constant offset to a ref, in a MACK_Addr context (meaning that the byref is not immediately // dereferenced). The alternative is "aggressive", which would not insert such checks (for // small offsets); in this plan, we would transfer some null-checking responsibility to // callee's of methods taking byref parameters. They would have to add explicit null checks // when creating derived byrefs from argument byrefs by adding constants to argument byrefs, in // contexts where the resulting derived byref is not immediately dereferenced (or if the offset is too // large). To make the "aggressive" scheme work, however, we'd also have to add explicit derived-from-null // checks for byref parameters to "external" methods implemented in C++, and in P/Invoke stubs. /// This is left here to point out how to implement it. #define CONSERVATIVE_NULL_CHECK_BYREF_CREATION 1 // If the objRef is a GT_ADDR node, it, itself, never requires null checking. The expression // whose address is being taken is either a local or static variable, whose address is necessarily // non-null, or else it is a field dereference, which will do its own bounds checking if necessary. if (objRef->gtOper != GT_ADDR && ((mac->m_kind == MACK_Addr || mac->m_kind == MACK_Ind) && (!mac->m_allConstantOffsets || fgIsBigOffset(mac->m_totalOffset + fldOffset) #if CONSERVATIVE_NULL_CHECK_BYREF_CREATION || (mac->m_kind == MACK_Addr && (mac->m_totalOffset + fldOffset > 0)) #else || (objRef->gtType == TYP_BYREF && mac->m_kind == MACK_Addr && (mac->m_totalOffset + fldOffset > 0)) #endif ))) { #ifdef DEBUG if (verbose) { printf("Before explicit null check morphing:\n"); gtDispTree(tree); } #endif // // Create the "comma" subtree // GenTreePtr asg = NULL; GenTreePtr nullchk; unsigned lclNum; if (objRef->gtOper != GT_LCL_VAR) { lclNum = fgGetBigOffsetMorphingTemp(genActualType(objRef->TypeGet())); // Create the "asg" node asg = gtNewTempAssign(lclNum, objRef); } else { lclNum = objRef->gtLclVarCommon.gtLclNum; } // Create the "nullchk" node nullchk = gtNewOperNode(GT_NULLCHECK, TYP_BYTE, // Make it TYP_BYTE so we only deference it for 1 byte. gtNewLclvNode(lclNum, objRefType)); nullchk->gtFlags |= GTF_DONT_CSE; // Don't try to create a CSE for these TYP_BYTE indirections /* An indirection will cause a GPF if the address is null */ nullchk->gtFlags |= GTF_EXCEPT; if (asg) { // Create the "comma" node. comma = gtNewOperNode(GT_COMMA, TYP_VOID, // We don't want to return anything from this "comma" node. // Set the type to TYP_VOID, so we can select "cmp" instruction // instead of "mov" instruction later on. asg, nullchk); } else { comma = nullchk; } addr = gtNewLclvNode(lclNum, objRefType); // Use "tmpLcl" to create "addr" node. addedExplicitNullCheck = true; } else if (fldOffset == 0) { // Generate the "addr" node. addr = objRef; FieldSeqNode* fieldSeq = fieldMayOverlap ? FieldSeqStore::NotAField() : GetFieldSeqStore()->CreateSingleton(symHnd); GetZeroOffsetFieldMap()->Set(addr, fieldSeq); } else { addr = objRef; } #ifdef FEATURE_READYTORUN_COMPILER if (tree->gtField.gtFieldLookup.addr != nullptr) { GenTreePtr baseOffset = gtNewIconEmbHndNode(tree->gtField.gtFieldLookup.addr, nullptr, GTF_ICON_FIELD_HDL); if (tree->gtField.gtFieldLookup.accessType == IAT_PVALUE) baseOffset = gtNewOperNode(GT_IND, TYP_I_IMPL, baseOffset); addr = gtNewOperNode(GT_ADD, (var_types)(objRefType == TYP_I_IMPL ? TYP_I_IMPL : TYP_BYREF), addr, baseOffset ); } #endif if (fldOffset != 0) { // Generate the "addr" node. /* Add the member offset to the object's address */ FieldSeqNode* fieldSeq = fieldMayOverlap ? FieldSeqStore::NotAField() : GetFieldSeqStore()->CreateSingleton(symHnd); addr = gtNewOperNode(GT_ADD, (var_types)(objRefType == TYP_I_IMPL ? TYP_I_IMPL : TYP_BYREF), addr, gtNewIconHandleNode(fldOffset, GTF_ICON_FIELD_OFF, fieldSeq)); } // Now let's set the "tree" as a GT_IND tree. tree->SetOper(GT_IND); tree->gtOp.gtOp1 = addr; if (fgAddrCouldBeNull(addr)) { // This indirection can cause a GPF if the address could be null. tree->gtFlags |= GTF_EXCEPT; } if (addedExplicitNullCheck) { // // Create "comma2" node and link it to "tree". // GenTreePtr comma2; comma2 = gtNewOperNode(GT_COMMA, addr->TypeGet(), // The type of "comma2" node is the same as the type of "addr" node. comma, addr); tree->gtOp.gtOp1 = comma2; } #ifdef DEBUG if (verbose) { if (addedExplicitNullCheck) { printf("After adding explicit null check:\n"); gtDispTree(tree); } } #endif } else /* This is a static data member */ { if (tree->gtFlags & GTF_IND_TLS_REF) { // Thread Local Storage static field reference // // Field ref is a TLS 'Thread-Local-Storage' reference // // Build this tree: IND(*) # // | // ADD(I_IMPL) // / \ // / CNS(fldOffset) // / // / // / // IND(I_IMPL) == [Base of this DLL's TLS] // | // ADD(I_IMPL) // / \ // / CNS(IdValue*4) or MUL // / / \ // IND(I_IMPL) / CNS(4) // | / // CNS(TLS_HDL,0x2C) IND // | // CNS(pIdAddr) // // # Denotes the orginal node // void ** pIdAddr = NULL; unsigned IdValue = info.compCompHnd->getFieldThreadLocalStoreID(symHnd, (void**) &pIdAddr); // // If we can we access the TLS DLL index ID value directly // then pIdAddr will be NULL and // IdValue will be the actual TLS DLL index ID // GenTreePtr dllRef = NULL; if (pIdAddr == NULL) { if (IdValue != 0) dllRef = gtNewIconNode(IdValue*4, TYP_I_IMPL); } else { dllRef = gtNewIconHandleNode((size_t)pIdAddr, GTF_ICON_STATIC_HDL); dllRef = gtNewOperNode(GT_IND, TYP_I_IMPL, dllRef); dllRef->gtFlags |= GTF_IND_INVARIANT; /* Multiply by 4 */ dllRef = gtNewOperNode(GT_MUL, TYP_I_IMPL, dllRef, gtNewIconNode(4, TYP_I_IMPL)); } #define WIN32_TLS_SLOTS (0x2C) // Offset from fs:[0] where the pointer to the slots resides // Mark this ICON as a TLS_HDL, codegen will use FS:[cns] GenTreePtr tlsRef = gtNewIconHandleNode(WIN32_TLS_SLOTS, GTF_ICON_TLS_HDL); tlsRef = gtNewOperNode(GT_IND, TYP_I_IMPL, tlsRef); if (dllRef != NULL) { /* Add the dllRef */ tlsRef = gtNewOperNode(GT_ADD, TYP_I_IMPL, tlsRef, dllRef); } /* indirect to have tlsRef point at the base of the DLLs Thread Local Storage */ tlsRef = gtNewOperNode(GT_IND, TYP_I_IMPL, tlsRef); if (fldOffset != 0) { FieldSeqNode* fieldSeq = fieldMayOverlap ? FieldSeqStore::NotAField() : GetFieldSeqStore()->CreateSingleton(symHnd); GenTreePtr fldOffsetNode = new(this, GT_CNS_INT) GenTreeIntCon(TYP_INT, fldOffset, fieldSeq); /* Add the TLS static field offset to the address */ tlsRef = gtNewOperNode(GT_ADD, TYP_I_IMPL, tlsRef, fldOffsetNode); } // Final indirect to get to actual value of TLS static field tree->SetOper(GT_IND); tree->gtOp.gtOp1 = tlsRef; noway_assert(tree->gtFlags & GTF_IND_TLS_REF); } else { // Normal static field reference // // If we can we access the static's address directly // then pFldAddr will be NULL and // fldAddr will be the actual address of the static field // void ** pFldAddr = NULL; void * fldAddr = info.compCompHnd->getFieldAddress(symHnd, (void**) &pFldAddr); if (pFldAddr == NULL) { #ifdef _TARGET_64BIT_ if (IMAGE_REL_BASED_REL32 != eeGetRelocTypeHint(fldAddr)) { // The address is not directly addressible, so force it into a // constant, so we handle it properly GenTreePtr addr = gtNewIconHandleNode((size_t)fldAddr, GTF_ICON_STATIC_HDL); addr->gtType = TYP_I_IMPL; FieldSeqNode* fieldSeq = fieldMayOverlap ? FieldSeqStore::NotAField() : GetFieldSeqStore()->CreateSingleton(symHnd); addr->gtIntCon.gtFieldSeq = fieldSeq; tree->SetOper(GT_IND); tree->gtOp.gtOp1 = addr; return fgMorphSmpOp(tree); } else #endif // _TARGET_64BIT_ { // Only volatile could be set, and it maps over noway_assert((tree->gtFlags & ~(GTF_FLD_VOLATILE | GTF_COMMON_MASK)) == 0); noway_assert(GTF_FLD_VOLATILE == GTF_IND_VOLATILE); tree->SetOper(GT_CLS_VAR); tree->gtClsVar.gtClsVarHnd = symHnd; FieldSeqNode* fieldSeq = fieldMayOverlap ? FieldSeqStore::NotAField() : GetFieldSeqStore()->CreateSingleton(symHnd); tree->gtClsVar.gtFieldSeq = fieldSeq; } return tree; } else { GenTreePtr addr = gtNewIconHandleNode((size_t)pFldAddr, GTF_ICON_STATIC_HDL); // There are two cases here, either the static is RVA based, // in which case the type of the FIELD node is not a GC type // and the handle to the RVA is a TYP_I_IMPL. Or the FIELD node is // a GC type and the handle to it is a TYP_BYREF in the GC heap // because handles to statics now go into the large object heap var_types handleTyp = (var_types) (varTypeIsGC(tree->TypeGet()) ? TYP_BYREF : TYP_I_IMPL); GenTreePtr op1 = gtNewOperNode(GT_IND, handleTyp, addr); op1->gtFlags |= GTF_IND_INVARIANT; tree->SetOper(GT_IND); tree->gtOp.gtOp1 = op1; } } } noway_assert(tree->gtOper == GT_IND); GenTreePtr res = fgMorphSmpOp(tree); if (fldOffset == 0 && res->OperGet() == GT_IND) { GenTreePtr addr = res->gtOp.gtOp1; // Since we don't make a constant zero to attach the field sequence to, associate it with the "addr" node. FieldSeqNode* fieldSeq = fieldMayOverlap ? FieldSeqStore::NotAField() : GetFieldSeqStore()->CreateSingleton(symHnd); fgAddFieldSeqForZeroOffset(addr, fieldSeq); } return res; } //------------------------------------------------------------------------------ // fgMorphCallInline: attempt to inline a call // // Arguments: // call - call expression to inline, inline candidate // inlineResult - result tracking and reporting // // Notes: // Attempts to inline the call. // // If successful, callee's IR is inserted in place of the call, and // is marked with an InlineContext. // // If unsuccessful, the transformations done in anticpation of a // possible inline are undone, and the candidate flag on the call // is cleared. void Compiler::fgMorphCallInline(GenTreeCall* call, InlineResult* inlineResult) { // The call must be a candiate for inlining. assert((call->gtFlags & GTF_CALL_INLINE_CANDIDATE) != 0); // Attempt the inline fgMorphCallInlineHelper(call, inlineResult); // We should have made up our minds one way or another.... assert(inlineResult->IsDecided()); // If we failed to inline, we have a bit of work to do to cleanup if (inlineResult->IsFailure()) { #ifdef DEBUG // Before we do any cleanup, create a failing InlineContext to // capture details of the inlining attempt. InlineContext::NewFailure(this, fgMorphStmt, inlineResult); #endif // It was an inline candidate, but we haven't expanded it. if (call->gtCall.gtReturnType != TYP_VOID) { // Detach the GT_CALL tree from the original statement by // hanging a "nothing" node to it. Later the "nothing" node will be removed // and the original GT_CALL tree will be picked up by the GT_RET_EXPR node. noway_assert(fgMorphStmt->gtStmt.gtStmtExpr == call); fgMorphStmt->gtStmt.gtStmtExpr = gtNewNothingNode(); } // Clear the Inline Candidate flag so we can ensure later we tried // inlining all candidates. // call->gtFlags &= ~GTF_CALL_INLINE_CANDIDATE; } } /***************************************************************************** * Helper to attempt to inline a call * Sets success/failure in inline result * If success, modifies current method's IR with inlinee's IR * If failed, undoes any speculative modifications to current method */ void Compiler::fgMorphCallInlineHelper(GenTreeCall* call, InlineResult* result) { // Don't expect any surprises here. assert(result->IsCandidate()); if (lvaCount >= MAX_LV_NUM_COUNT_FOR_INLINING) { // For now, attributing this to call site, though it's really // more of a budget issue (lvaCount currently includes all // caller and prospective callee locals). We still might be // able to inline other callees into this caller, or inline // this callee in other callers. result->NoteFatal(InlineObservation::CALLSITE_TOO_MANY_LOCALS); return; } if (call->IsVirtual()) { result->NoteFatal(InlineObservation::CALLSITE_IS_VIRTUAL); return; } // impMarkInlineCandidate() is expected not to mark tail prefixed calls // and recursive tail calls as inline candidates. noway_assert(!call->IsTailPrefixedCall()); noway_assert(!call->IsImplicitTailCall() || !gtIsRecursiveCall(call)); /* If the caller's stack frame is marked, then we can't do any inlining. Period. Although we have checked this in impCanInline, it is possible that later IL instructions might cause compNeedSecurityCheck to be set. Therefore we need to check it here again. */ if (opts.compNeedSecurityCheck) { result->NoteFatal(InlineObservation::CALLER_NEEDS_SECURITY_CHECK); return; } // // Calling inlinee's compiler to inline the method. // unsigned startVars = lvaCount; #ifdef DEBUG if (verbose) { printf("Expanding INLINE_CANDIDATE in statement "); printTreeID(fgMorphStmt); printf(" in BB%02u:\n", compCurBB->bbNum); gtDispTree(fgMorphStmt); // printf("startVars=%d.\n", startVars); } #endif // // Invoke the compiler to inline the call. // fgInvokeInlineeCompiler(call, result); if (result->IsFailure()) { // Undo some changes made in anticipation of inlining... // Zero out the used locals memset(lvaTable + startVars, 0, (lvaCount - startVars) * sizeof(*lvaTable)); for (unsigned i = startVars; i < lvaCount; i++) { new (&lvaTable[i], jitstd::placement_t()) LclVarDsc(this); // call the constructor. } lvaCount = startVars; #ifdef DEBUG if (verbose) { // printf("Inlining failed. Restore lvaCount to %d.\n", lvaCount); } #endif return; } // Success! #ifdef DEBUG if (verbose) { // printf("After inlining lvaCount=%d.\n", lvaCount); } #endif #if defined(DEBUG) || MEASURE_INLINING ++Compiler::jitTotalMethodInlined; #endif } /***************************************************************************** * * Performs checks to see if this tail call can be optimized as epilog+jmp. */ bool Compiler::fgCanFastTailCall(GenTreeCall* callee) { #if FEATURE_FASTTAILCALL // Reached here means that return types of caller and callee are tail call compatible. // In case of structs that can be returned in a register, compRetNativeType is set to the actual return type. // // In an implicit tail call case callSig may not be available but it is guaranteed to be available // for explicit tail call cases. The reason implicit tail case callSig may not be available is that // a call node might be marked as an in-line candidate and could fail to be in-lined. In which case // fgInline() will replace return value place holder with call node using gtCloneExpr() which is // currently not copying/setting callSig. #ifdef DEBUG if (callee->IsTailPrefixedCall()) { assert(impTailCallRetTypeCompatible(info.compRetNativeType, info.compMethodInfo->args.retTypeClass, (var_types)callee->gtReturnType, callee->callSig->retTypeClass)); } #endif // Note on vararg methods: // If the caller is vararg method, we don't know the number of arguments passed by caller's caller. // But we can be sure that in-coming arg area of vararg caller would be sufficient to hold its // fixed args. Therefore, we can allow a vararg method to fast tail call other methods as long as // out-going area required for callee is bounded by caller's fixed argument space. // // Note that callee being a vararg method is not a problem since we can account the params being passed. // Count of caller args including implicit and hidden (i.e. thisPtr, RetBuf, GenericContext, VarargCookie) unsigned nCallerArgs = info.compArgsCount; // Count the callee args including implicit and hidden. // Note that GenericContext and VarargCookie are added by importer while // importing the call to gtCallArgs list along with explicit user args. unsigned nCalleeArgs = 0; if (callee->gtCallObjp) // thisPtr { nCalleeArgs++; } if (callee->gtCallMoreFlags & GTF_CALL_M_RETBUFFARG) // RetBuf { nCalleeArgs++; // If callee has RetBuf param, caller too must have it. // Otherwise go the slow route. if (info.compRetBuffArg == BAD_VAR_NUM) { return false; } } // Count user args while tracking whether any of them is a multi-byte params // that cannot be passed in a register. Note that we don't need to count // non-standard and secret params passed in registers (e.g. R10, R11) since // these won't contribute to out-going arg size. bool hasMultiByteArgs = false; for (GenTreePtr args = callee->gtCallArgs; (args != nullptr) && !hasMultiByteArgs; args = args->gtOp.gtOp2) { nCalleeArgs++; assert(args->IsList()); GenTreePtr argx = args->gtOp.gtOp1; if (varTypeIsStruct(argx)) { // Actual arg may be a child of a GT_COMMA. Skip over comma opers. while (argx->gtOper == GT_COMMA) { argx = argx->gtOp.gtOp2; } // Get the size of the struct and see if it is register passable. if (argx->OperGet() == GT_OBJ) { #ifdef _TARGET_AMD64_ unsigned typeSize = 0; hasMultiByteArgs = !VarTypeIsMultiByteAndCanEnreg(argx->TypeGet(), argx->gtObj.gtClass, &typeSize, false); #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) // On System V the args could be a 2 eightbyte struct that is passed in two registers. // Account for the second eightbyte in the nCalleeArgs. // TODO-CQ-Amd64-Unix: Structs of size between 9 to 16 bytes are conservatively estimated // as two args, since they need two registers. Whereas nCallerArgs is // counting such an arg as one.This would mean we will not be optimizing // certain calls though technically possible. if (typeSize > TARGET_POINTER_SIZE) { unsigned extraArgRegsToAdd = (typeSize / TARGET_POINTER_SIZE); nCalleeArgs += extraArgRegsToAdd; } #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) #else assert(!"Target platform ABI rules regarding passing struct type args in registers"); unreached(); #endif //_TARGET_AMD64_ } else { hasMultiByteArgs = true; } } } // Go the slow route, if it has multi-byte params if (hasMultiByteArgs) { return false; } // If we reached here means that callee has only those argument types which can be passed in // a register and if passed on stack will occupy exactly one stack slot in out-going arg area. // If we are passing args on stack for callee and it has more args passed on stack than // caller, then fast tail call cannot be performed. // // Note that the GC'ness of on stack args need not match since the arg setup area is marked // as non-interruptible for fast tail calls. if ((nCalleeArgs > MAX_REG_ARG) && (nCallerArgs < nCalleeArgs)) { return false; } return true; #else return false; #endif } /***************************************************************************** * * Transform the given GT_CALL tree for tail call code generation. */ void Compiler::fgMorphTailCall(GenTreeCall* call) { // x86 classic codegen doesn't require any morphing #if defined(_TARGET_X86_) && !defined(LEGACY_BACKEND) NYI_X86("Tail call morphing"); #elif defined(_TARGET_ARM_) // For the helper-assisted tail calls, we need to push all the arguments // into a single list, and then add a few extra at the beginning // Check for PInvoke call types that we don't handle in codegen yet. assert(!call->IsUnmanaged()); assert(call->IsVirtual() || (call->gtCallType != CT_INDIRECT) || (call->gtCallCookie == NULL)); // First move the this pointer (if any) onto the regular arg list GenTreePtr thisPtr = NULL; if (call->gtCallObjp) { GenTreePtr objp = call->gtCallObjp; call->gtCallObjp = NULL; if ((call->gtFlags & GTF_CALL_NULLCHECK) || call->IsVirtualVtable()) { thisPtr = gtClone(objp, true); var_types vt = objp->TypeGet(); if (thisPtr == NULL) { // Too complex, so use a temp unsigned lclNum = lvaGrabTemp(true DEBUGARG("tail call thisptr")); GenTreePtr asg = gtNewTempAssign(lclNum, objp); if (!call->IsVirtualVtable()) { // Add an indirection to get the nullcheck GenTreePtr tmp = gtNewLclvNode(lclNum, vt); GenTreePtr ind = gtNewOperNode(GT_IND, TYP_INT, tmp); asg = gtNewOperNode(GT_COMMA, TYP_VOID, asg, ind); } objp = gtNewOperNode(GT_COMMA, vt, asg, gtNewLclvNode(lclNum, vt)); thisPtr = gtNewLclvNode(lclNum, vt); } else if (!call->IsVirtualVtable()) { GenTreePtr ind = gtNewOperNode(GT_IND, TYP_INT, thisPtr); objp = gtNewOperNode(GT_COMMA, vt, ind, objp); thisPtr = gtClone(thisPtr, true); } call->gtFlags &= ~GTF_CALL_NULLCHECK; } GenTreeArgList** pList = &call->gtCallArgs; #if RETBUFARG_PRECEDES_THIS if (call->gtCallMoreFlags & GTF_CALL_M_RETBUFFARG) { pList = &(*pList)->Rest(); } #endif // RETBUFARG_PRECEDES_THIS *pList = gtNewListNode(objp, *pList); } // Add the extra VSD parameter if needed CorInfoHelperTailCallSpecialHandling flags = CorInfoHelperTailCallSpecialHandling(0); if (call->IsVirtualStub()) { flags = CORINFO_TAILCALL_STUB_DISPATCH_ARG; GenTreePtr arg; if (call->gtCallType == CT_INDIRECT) { arg = gtClone(call->gtCallAddr, true); noway_assert(arg != NULL); } else { noway_assert(call->gtCallMoreFlags & GTF_CALL_M_VIRTSTUB_REL_INDIRECT); ssize_t addr = ssize_t(call->gtStubCallStubAddr); arg = gtNewIconHandleNode(addr, GTF_ICON_FTN_ADDR); // Change the call type, so we can add the extra indirection here, rather than in codegen call->gtCallAddr = gtNewIconHandleNode(addr, GTF_ICON_FTN_ADDR); call->gtStubCallStubAddr = NULL; call->gtCallType = CT_INDIRECT; } // Add the extra indirection to generate the real target call->gtCallAddr = gtNewOperNode(GT_IND, TYP_I_IMPL, call->gtCallAddr); call->gtFlags |= GTF_EXCEPT; // And push the stub address onto the list of arguments call->gtCallArgs = gtNewListNode(arg, call->gtCallArgs); } else if (call->IsVirtualVtable()) { // TODO-ARM-NYI: for x64 handle CORINFO_TAILCALL_THIS_IN_SECRET_REGISTER noway_assert(thisPtr != NULL); GenTreePtr add = gtNewOperNode(GT_ADD, TYP_I_IMPL, thisPtr, gtNewIconNode(VPTR_OFFS, TYP_I_IMPL)); GenTreePtr vtbl = gtNewOperNode(GT_IND, TYP_I_IMPL, add); vtbl->gtFlags |= GTF_EXCEPT; unsigned vtabOffsOfIndirection; unsigned vtabOffsAfterIndirection; info.compCompHnd->getMethodVTableOffset(call->gtCallMethHnd, &vtabOffsOfIndirection, &vtabOffsAfterIndirection); /* Get the appropriate vtable chunk */ add = gtNewOperNode(GT_ADD, TYP_I_IMPL, vtbl, gtNewIconNode(vtabOffsOfIndirection, TYP_I_IMPL)); vtbl = gtNewOperNode(GT_IND, TYP_I_IMPL, add); /* Now the appropriate vtable slot */ add = gtNewOperNode(GT_ADD, TYP_I_IMPL, vtbl, gtNewIconNode(vtabOffsAfterIndirection, TYP_I_IMPL)); vtbl = gtNewOperNode(GT_IND, TYP_I_IMPL, add); // Switch this to a plain indirect call call->gtFlags &= ~GTF_CALL_VIRT_KIND_MASK; assert(!call->IsVirtual()); call->gtCallType = CT_INDIRECT; call->gtCallAddr = vtbl; call->gtCallCookie = NULL; call->gtFlags |= GTF_EXCEPT; } // Now inject a placeholder for the real call target that codegen // will generate GenTreePtr arg = new (this, GT_NOP) GenTreeOp(GT_NOP, TYP_I_IMPL); codeGen->genMarkTreeInReg(arg, REG_TAILCALL_ADDR); call->gtCallArgs = gtNewListNode(arg, call->gtCallArgs); // Lastly inject the pointer for the copy routine noway_assert(call->callSig != NULL); void * pfnCopyArgs = info.compCompHnd->getTailCallCopyArgsThunk(call->callSig, flags); arg = gtNewIconHandleNode(ssize_t(pfnCopyArgs), GTF_ICON_FTN_ADDR); call->gtCallArgs = gtNewListNode(arg, call->gtCallArgs); // It is now a varargs tail call call->gtCallMoreFlags = GTF_CALL_M_VARARGS | GTF_CALL_M_TAILCALL; call->gtFlags &= ~GTF_CALL_POP_ARGS; #elif defined(_TARGET_AMD64_) // For the helper-assisted tail calls, we need to push all the arguments // into a single list, and then add a few extra at the beginning. // // TailCallHelper(void *copyRoutine, void *callTarget, ....) - i.e We need to add // copyRoutine and callTarget extra params at the beginning. But callTarget is // determined by Lower phase. Therefore, we add a place holder arg for callTarget // here which will be later replaced with callTarget in tail call lowering. // Check for PInvoke call types that we don't handle in codegen yet. assert(!call->IsUnmanaged()); assert(call->IsVirtual() || (call->gtCallType != CT_INDIRECT) || (call->gtCallCookie == NULL)); // Don't support tail calling helper methods assert(call->gtCallType != CT_HELPER); // We come this route only for tail prefixed calls that cannot be dispatched as // fast tail calls assert(!call->IsImplicitTailCall()); assert(!fgCanFastTailCall(call)); // First move the this pointer (if any) onto the regular arg list if (call->gtCallObjp) { GenTreePtr thisPtr = nullptr; GenTreePtr objp = call->gtCallObjp; call->gtCallObjp = nullptr; if (call->NeedsNullCheck()) { // clone "this" if "this" has no side effects. if (!(objp->gtFlags & GTF_SIDE_EFFECT)) { thisPtr = gtClone(objp, true); } var_types vt = objp->TypeGet(); if (thisPtr == nullptr) { // create a temp if either "this" has side effects or "this" is too complex to clone. // tmp = "this" unsigned lclNum = lvaGrabTemp(true DEBUGARG("tail call thisptr")); GenTreePtr asg = gtNewTempAssign(lclNum, objp); // COMMA(tmp = "this", deref(tmp)) GenTreePtr tmp = gtNewLclvNode(lclNum, vt); GenTreePtr ind = gtNewOperNode(GT_IND, TYP_INT, tmp); asg = gtNewOperNode(GT_COMMA, TYP_VOID, asg, ind); // COMMA(COMMA(tmp = "this", deref(tmp)), tmp) thisPtr = gtNewOperNode(GT_COMMA, vt, asg, gtNewLclvNode(lclNum, vt)); } else { // thisPtr = COMMA(deref("this"), "this") GenTreePtr ind = gtNewOperNode(GT_IND, TYP_INT, thisPtr); thisPtr = gtNewOperNode(GT_COMMA, vt, ind, gtClone(objp, true)); } call->gtFlags &= ~GTF_CALL_NULLCHECK; } else { thisPtr = objp; } GenTreeArgList** pList = &call->gtCallArgs; #if RETBUFARG_PRECEDES_THIS if (call->gtCallMoreFlags & GTF_CALL_M_RETBUFFARG) { pList = &(*pList)->Rest(); } #endif // RETBUFARG_PRECEDES_THIS // During rationalization tmp="this" and null check will // materialize as embedded stmts in right execution order. assert(thisPtr != nullptr); *pList = gtNewListNode(thisPtr, *pList); } // Add the extra VSD parameter to arg list in case of VSD calls. // Tail call arg copying thunk will move this extra VSD parameter // to R11 before tail calling VSD stub. See CreateTailCallCopyArgsThunk() // in Stublinkerx86.cpp for more details. CorInfoHelperTailCallSpecialHandling flags = CorInfoHelperTailCallSpecialHandling(0); if (call->IsVirtualStub()) { GenTreePtr stubAddrArg; flags = CORINFO_TAILCALL_STUB_DISPATCH_ARG; if (call->gtCallType == CT_INDIRECT) { stubAddrArg = gtClone(call->gtCallAddr, true); noway_assert(stubAddrArg != nullptr); } else { noway_assert((call->gtCallMoreFlags & GTF_CALL_M_VIRTSTUB_REL_INDIRECT) != 0); ssize_t addr = ssize_t(call->gtStubCallStubAddr); stubAddrArg = gtNewIconHandleNode(addr, GTF_ICON_FTN_ADDR); } // Push the stub address onto the list of arguments call->gtCallArgs = gtNewListNode(stubAddrArg, call->gtCallArgs); } // Now inject a placeholder for the real call target that Lower phase will generate. GenTreePtr arg = gtNewIconNode(0, TYP_I_IMPL); call->gtCallArgs = gtNewListNode(arg, call->gtCallArgs); // Inject the pointer for the copy routine to be used for struct copying noway_assert(call->callSig != nullptr); void * pfnCopyArgs = info.compCompHnd->getTailCallCopyArgsThunk(call->callSig, flags); arg = gtNewIconHandleNode(ssize_t(pfnCopyArgs), GTF_ICON_FTN_ADDR); call->gtCallArgs = gtNewListNode(arg, call->gtCallArgs); // It is now a varargs tail call dispatched via helper. call->gtCallMoreFlags |= GTF_CALL_M_VARARGS | GTF_CALL_M_TAILCALL | GTF_CALL_M_TAILCALL_VIA_HELPER; call->gtFlags &= ~GTF_CALL_POP_ARGS; #endif //_TARGET_AMD64_ } //------------------------------------------------------------------------------ // fgMorphRecursiveFastTailCallIntoLoop : Transform a recursive fast tail call into a loop. // // // Arguments: // block - basic block ending with a recursive fast tail call // recursiveTailCall - recursive tail call to transform // // Notes: // The legality of the transformation is ensured by the checks in endsWithTailCallConvertibleToLoop. void Compiler::fgMorphRecursiveFastTailCallIntoLoop(BasicBlock* block, GenTreeCall* recursiveTailCall) { assert(recursiveTailCall->IsTailCallConvertibleToLoop()); GenTreePtr last = fgGetLastTopLevelStmt(block); assert(recursiveTailCall == last->gtStmt.gtStmtExpr); // Transform recursive tail call into a loop. GenTreePtr earlyArgInsertionPoint = last; IL_OFFSETX callILOffset = last->gtStmt.gtStmtILoffsx; // Hoist arg setup statement for the 'this' argument. GenTreePtr thisArg = recursiveTailCall->gtCallObjp; if (thisArg && !thisArg->IsNothingNode() && !thisArg->IsArgPlaceHolderNode()) { GenTreePtr thisArgStmt = gtNewStmt(thisArg, callILOffset); fgInsertStmtBefore(block, earlyArgInsertionPoint, thisArgStmt); } // All arguments whose trees may involve caller parameter local variables need to be assigned to temps first; // then the temps need to be assigned to the method parameters. This is done so that the caller // parameters are not re-assigned before call arguments depending on them are evaluated. // tmpAssignmentInsertionPoint and paramAssignmentInsertionPoint keep track of // where the next temp or parameter assignment should be inserted. // In the example below the first call argument (arg1 - 1) needs to be assigned to a temp first // while the second call argument (const 1) doesn't. // Basic block before tail recursion elimination: // ***** BB04, stmt 1 (top level) // [000037] ------------ * stmtExpr void (top level) (IL 0x00A...0x013) // [000033] --C - G------ - \--* call void RecursiveMethod // [000030] ------------ | / --* const int - 1 // [000031] ------------arg0 in rcx + --* +int // [000029] ------------ | \--* lclVar int V00 arg1 // [000032] ------------arg1 in rdx \--* const int 1 // // // Basic block after tail recursion elimination : // ***** BB04, stmt 1 (top level) // [000051] ------------ * stmtExpr void (top level) (IL 0x00A... ? ? ? ) // [000030] ------------ | / --* const int - 1 // [000031] ------------ | / --* +int // [000029] ------------ | | \--* lclVar int V00 arg1 // [000050] - A---------- \--* = int // [000049] D------N---- \--* lclVar int V02 tmp0 // // ***** BB04, stmt 2 (top level) // [000055] ------------ * stmtExpr void (top level) (IL 0x00A... ? ? ? ) // [000052] ------------ | / --* lclVar int V02 tmp0 // [000054] - A---------- \--* = int // [000053] D------N---- \--* lclVar int V00 arg0 // ***** BB04, stmt 3 (top level) // [000058] ------------ * stmtExpr void (top level) (IL 0x00A... ? ? ? ) // [000032] ------------ | / --* const int 1 // [000057] - A---------- \--* = int // [000056] D------N---- \--* lclVar int V01 arg1 GenTreePtr tmpAssignmentInsertionPoint = last; GenTreePtr paramAssignmentInsertionPoint = last; // Process early args. They may contain both setup statements for late args and actual args. // Early args don't include 'this' arg. We need to account for that so that the call to gtArgEntryByArgNum // below has the correct second argument. int earlyArgIndex = (thisArg == nullptr) ? 0 : 1; for (GenTreeArgList* earlyArgs = recursiveTailCall->gtCallArgs; earlyArgs != nullptr; (earlyArgIndex++, earlyArgs = earlyArgs->Rest())) { GenTreePtr earlyArg = earlyArgs->Current(); if (!earlyArg->IsNothingNode() && !earlyArg->IsArgPlaceHolderNode()) { if ((earlyArg->gtFlags & GTF_LATE_ARG) != 0) { // This is a setup node so we need to hoist it. GenTreePtr earlyArgStmt = gtNewStmt(earlyArg, callILOffset); fgInsertStmtBefore(block, earlyArgInsertionPoint, earlyArgStmt); } else { // This is an actual argument that needs to be assigned to the corresponding caller parameter. fgArgTabEntryPtr curArgTabEntry = gtArgEntryByArgNum(recursiveTailCall, earlyArgIndex); GenTreePtr paramAssignStmt = fgAssignRecursiveCallArgToCallerParam(earlyArg, curArgTabEntry, block, callILOffset, tmpAssignmentInsertionPoint, paramAssignmentInsertionPoint); if ((tmpAssignmentInsertionPoint == last) && (paramAssignStmt != nullptr)) { // All temp assignments will happen before the first param assignment. tmpAssignmentInsertionPoint = paramAssignStmt; } } } } // Process late args. int lateArgIndex = 0; for (GenTreeArgList* lateArgs = recursiveTailCall->gtCallLateArgs; lateArgs != nullptr; (lateArgIndex++, lateArgs = lateArgs->Rest())) { // A late argument is an actual argument that needs to be assigned to the corresponding caller's parameter. GenTreePtr lateArg = lateArgs->Current(); fgArgTabEntryPtr curArgTabEntry = gtArgEntryByLateArgIndex(recursiveTailCall, lateArgIndex); GenTreePtr paramAssignStmt = fgAssignRecursiveCallArgToCallerParam(lateArg, curArgTabEntry, block, callILOffset, tmpAssignmentInsertionPoint, paramAssignmentInsertionPoint); if ((tmpAssignmentInsertionPoint == last) && (paramAssignStmt != nullptr)) { // All temp assignments will happen before the first param assignment. tmpAssignmentInsertionPoint = paramAssignStmt; } } // If the method has starg.s 0 or ldarga.s 0 a special local (lvaArg0Var) is created so that // compThisArg stays immutable. Normally it's assigned in fgFirstBBScratch block. Since that // block won't be in the loop (it's assumed to have no predecessors), we need to update the special local here. if (!info.compIsStatic && (lvaArg0Var != info.compThisArg)) { var_types thisType = lvaTable[info.compThisArg].TypeGet(); GenTreePtr arg0 = gtNewLclvNode(lvaArg0Var, thisType); GenTreePtr arg0Assignment = gtNewAssignNode(arg0, gtNewLclvNode(info.compThisArg, thisType)); GenTreePtr arg0AssignmentStmt = gtNewStmt(arg0Assignment, callILOffset); fgInsertStmtBefore(block, paramAssignmentInsertionPoint, arg0AssignmentStmt); } // Remove the call fgRemoveStmt(block, last); // Set the loop edge. block->bbJumpKind = BBJ_ALWAYS; block->bbJumpDest = fgFirstBBisScratch() ? fgFirstBB->bbNext : fgFirstBB; fgAddRefPred(block->bbJumpDest, block); block->bbFlags &= ~BBF_HAS_JMP; } //------------------------------------------------------------------------------ // fgAssignRecursiveCallArgToCallerParam : Assign argument to a recursive call to the corresponding caller parameter. // // // Arguments: // arg - argument to assign // argTabEntry - argument table entry corresponding to arg // block --- basic block the call is in // callILOffset - IL offset of the call // tmpAssignmentInsertionPoint - tree before which temp assignment should be inserted (if necessary) // paramAssignmentInsertionPoint - tree before which parameter assignment should be inserted // // Return Value: // parameter assignment statement if one was inserted; nullptr otherwise. GenTreePtr Compiler::fgAssignRecursiveCallArgToCallerParam(GenTreePtr arg, fgArgTabEntryPtr argTabEntry, BasicBlock *block, IL_OFFSETX callILOffset, GenTreePtr tmpAssignmentInsertionPoint, GenTreePtr paramAssignmentInsertionPoint) { // Call arguments should be assigned to temps first and then the temps should be assigned to parameters because // some argument trees may reference parameters directly. GenTreePtr argInTemp = nullptr; unsigned originalArgNum = argTabEntry->argNum; bool needToAssignParameter = true; // TODO-CQ: enable calls with struct arguments passed in registers. noway_assert(!varTypeIsStruct(arg->TypeGet())); if ((argTabEntry->isTmp) || arg->IsCnsIntOrI() || arg->IsCnsFltOrDbl()) { // The argument is already assigned to a temp or is a const. argInTemp = arg; } else if (arg->OperGet() == GT_LCL_VAR) { unsigned lclNum = arg->AsLclVar()->gtLclNum; LclVarDsc * varDsc = &lvaTable[lclNum]; if (!varDsc->lvIsParam) { // The argument is a non-parameter local so it doesn't need to be assigned to a temp. argInTemp = arg; } else if (lclNum == originalArgNum) { // The argument is the same parameter local that we were about to assign so // we can skip the assignment. needToAssignParameter = false; } } // TODO: We don't need temp assignments if we can prove that the argument tree doesn't involve // any caller parameters. Some common cases are handled above but we may be able to eliminate // more temp assignments. GenTreePtr paramAssignStmt = nullptr; if (needToAssignParameter) { if (argInTemp == nullptr) { // The argument is not assigned to a temp. We need to create a new temp and insert an assignment. // TODO: we can avoid a temp assignment if we can prove that the argument tree // doesn't involve any caller parameters. unsigned tmpNum = lvaGrabTemp(true DEBUGARG("arg temp")); GenTreePtr tempSrc = arg; GenTreePtr tempDest = gtNewLclvNode(tmpNum, tempSrc->gtType); GenTreePtr tmpAssignNode = gtNewAssignNode(tempDest, tempSrc); GenTreePtr tmpAssignStmt = gtNewStmt(tmpAssignNode, callILOffset); fgInsertStmtBefore(block, tmpAssignmentInsertionPoint, tmpAssignStmt); argInTemp = gtNewLclvNode(tmpNum, tempSrc->gtType); } // Now assign the temp to the parameter. LclVarDsc *paramDsc = lvaTable + originalArgNum; assert(paramDsc->lvIsParam); GenTreePtr paramDest = gtNewLclvNode(originalArgNum, paramDsc->lvType); GenTreePtr paramAssignNode = gtNewAssignNode(paramDest, argInTemp); paramAssignStmt = gtNewStmt(paramAssignNode, callILOffset); fgInsertStmtBefore(block, paramAssignmentInsertionPoint, paramAssignStmt); } return paramAssignStmt; } /***************************************************************************** * * Transform the given GT_CALL tree for code generation. */ GenTreePtr Compiler::fgMorphCall(GenTreeCall* call) { if (call->CanTailCall()) { // It should either be an explicit (i.e. tail prefixed) or an implicit tail call assert(call->IsTailPrefixedCall() ^ call->IsImplicitTailCall()); // It cannot be an inline candidate assert(!call->IsInlineCandidate()); const char * szFailReason = nullptr; bool hasStructParam = false; if (call->gtCallMoreFlags & GTF_CALL_M_SPECIAL_INTRINSIC) { szFailReason = "Might turn into an intrinsic"; } if (opts.compNeedSecurityCheck) { szFailReason = "Needs security check"; } else if (compLocallocUsed) { szFailReason = "Localloc used"; } #ifdef _TARGET_AMD64_ // Needed for Jit64 compat. // In future, enabling tail calls from methods that need GS cookie check // would require codegen side work to emit GS cookie check before a tail // call. else if (getNeedsGSSecurityCookie()) { szFailReason = "GS Security cookie check"; } #endif #ifdef DEBUG // DDB 99324: Just disable tailcall under compGcChecks stress mode. else if (opts.compGcChecks) { szFailReason = "GcChecks"; } #endif #if FEATURE_TAILCALL_OPT else { // We are still not sure whether it can be a tail call. Because, when converting // a call to an implicit tail call, we must check that there are no locals with // their address taken. If this is the case, we have to assume that the address // has been leaked and the current stack frame must live until after the final // call. // Verify that none of vars has lvHasLdAddrOp or lvAddrExposed bit set. Note // that lvHasLdAddrOp is much more conservative. We cannot just base it on // lvAddrExposed alone since it is not guaranteed to be set on all VarDscs // during morph stage. The reason for also checking lvAddrExposed is that in case // of vararg methods user args are marked as addr exposed but not lvHasLdAddrOp. // The combination of lvHasLdAddrOp and lvAddrExposed though conservative allows us // never to be incorrect. // // TODO-Throughput: have a compiler level flag to indicate whether method has vars whose // address is taken. Such a flag could be set whenever lvHasLdAddrOp or LvAddrExposed // is set. This avoids the need for iterating through all lcl vars of the current // method. Right now throughout the code base we are not consistently using 'set' // method to set lvHasLdAddrOp and lvAddrExposed flags. unsigned varNum; LclVarDsc *varDsc; bool hasAddrExposedVars = false; bool hasStructPromotedParam = false; bool hasPinnedVars = false; for (varNum = 0, varDsc = lvaTable; varNum < lvaCount; varNum++, varDsc++) { // If the method is marked as an explicit tail call we will skip the // following three hazard checks. // We still must check for any struct parameters and set 'hasStructParam' // so that we won't transform the recursive tail call into a loop. // if (call->IsImplicitTailCall()) { if (varDsc->lvHasLdAddrOp || varDsc->lvAddrExposed) { hasAddrExposedVars = true; break; } if (varDsc->lvPromoted && varDsc->lvIsParam) { hasStructPromotedParam = true; break; } if (varDsc->lvPinned) { // A tail call removes the method from the stack, which means the pinning // goes away for the callee. We can't allow that. hasPinnedVars = true; break; } } if (varTypeIsStruct(varDsc->TypeGet()) && varDsc->lvIsParam) { hasStructParam = true; // This prevents transforming a recursive tail call into a loop // but doesn't prevent tail call optimization so we need to // look at the rest of parameters. continue; } } if (hasAddrExposedVars) { szFailReason = "Local address taken"; } if (hasStructPromotedParam) { szFailReason = "Has Struct Promoted Param"; } if (hasPinnedVars) { szFailReason = "Has Pinned Vars"; } } #endif // FEATURE_TAILCALL_OPT fgFixupStructReturn(call); var_types callType = call->TypeGet(); // We have to ensure to pass the incoming retValBuf as the // outgoing one. Using a temp will not do as this function will // not regain control to do the copy. if (info.compRetBuffArg != BAD_VAR_NUM) { noway_assert(callType == TYP_VOID); GenTreePtr retValBuf = call->gtCallArgs->gtOp.gtOp1; if (retValBuf->gtOper != GT_LCL_VAR || retValBuf->gtLclVarCommon.gtLclNum != info.compRetBuffArg) { szFailReason = "Need to copy return buffer"; } } // If this is an opportunistic tail call and cannot be dispatched as // fast tail call, go the non-tail call route. This is done for perf // reason. // // Avoid the cost of determining whether can be dispatched as fast tail // call if we already know that tail call cannot be honored for other // reasons. bool canFastTailCall = false; if (szFailReason == nullptr) { canFastTailCall = fgCanFastTailCall(call); if (!canFastTailCall) { // Implicit or opportunistic tail calls are always dispatched via fast tail call // mechanism and never via tail call helper for perf. if (call->IsImplicitTailCall()) { szFailReason = "Opportunistic tail call cannot be dispatched as epilog+jmp"; } #ifndef LEGACY_BACKEND else if (!call->IsVirtualStub() && call->HasNonStandardArgs()) { // If we are here, it means that the call is an explicitly ".tail" prefixed and cannot be // dispatched as a fast tail call. // Methods with non-standard args will have indirection cell or cookie param passed // in callee trash register (e.g. R11). Tail call helper doesn't preserve it before // tail calling the target method and hence ".tail" prefix on such calls needs to be // ignored. // // Exception to the above rule: although Virtual Stub Dispatch (VSD) calls though require // extra stub param (e.g. in R11 on Amd64), they can still be called via tail call helper. // This is done by by adding stubAddr as an additional arg before the original list of // args. For more details see fgMorphTailCall() and CreateTailCallCopyArgsThunk() // in Stublinkerx86.cpp. szFailReason = "Method with non-standard args passed in callee trash register cannot be tail called via helper"; } #endif //LEGACY_BACKEND } } // Clear these flags before calling fgMorphCall() to avoid recursion. bool isTailPrefixed = call->IsTailPrefixedCall(); call->gtCallMoreFlags &= ~GTF_CALL_M_EXPLICIT_TAILCALL; #if FEATURE_TAILCALL_OPT call->gtCallMoreFlags &= ~GTF_CALL_M_IMPLICIT_TAILCALL; #endif #ifdef FEATURE_PAL if (!canFastTailCall && szFailReason == nullptr) { szFailReason = "Non fast tail calls disabled for PAL based systems."; } #endif // FEATURE_PAL if (szFailReason != nullptr) { #ifdef DEBUG if (verbose) { printf("\nRejecting tail call late for call "); printTreeID(call); printf(": %s\n", szFailReason); } #endif // for non user funcs, we have no handles to report info.compCompHnd->reportTailCallDecision(nullptr, (call->gtCallType == CT_USER_FUNC) ? call->gtCallMethHnd : nullptr, isTailPrefixed, TAILCALL_FAIL, szFailReason); goto NO_TAIL_CALL; } #if !FEATURE_TAILCALL_OPT_SHARED_RETURN // We enable shared-ret tail call optimization for recursive calls even if // FEATURE_TAILCALL_OPT_SHARED_RETURN is not defined. if (gtIsRecursiveCall(call)) #endif { // Many tailcalls will have call and ret in the same block, and thus be BBJ_RETURN, // but if the call falls through to a ret, and we are doing a tailcall, change it here. if (compCurBB->bbJumpKind != BBJ_RETURN) compCurBB->bbJumpKind = BBJ_RETURN; } // Set this flag before calling fgMorphCall() to prevent inlining this call. call->gtCallMoreFlags |= GTF_CALL_M_TAILCALL; bool fastTailCallToLoop = false; #if FEATURE_TAILCALL_OPT // TODO-CQ: enable the transformation when the method has a struct parameter that can be passed in a register // or return type is a struct that can be passed in a register. // // TODO-CQ: if the method being compiled requires generic context reported in gc-info (either through // hidden generic context param or through keep alive thisptr), then while transforming a recursive // call to such a method requires that the generic context stored on stack slot be updated. Right now, // fgMorphRecursiveFastTailCallIntoLoop() is not handling update of generic context while transforming // a recursive call into a loop. Another option is to modify gtIsRecursiveCall() to check that the // generic type parameters of both caller and callee generic method are the same. if (opts.compTailCallLoopOpt && canFastTailCall && gtIsRecursiveCall(call) && !lvaReportParamTypeArg() && !lvaKeepAliveAndReportThis() && !call->IsVirtual() && !hasStructParam && !varTypeIsStruct(call->TypeGet())) { call->gtCallMoreFlags |= GTF_CALL_M_TAILCALL_TO_LOOP; fastTailCallToLoop = true; } #endif // Do some target-specific transformations (before we process the args, etc.) // This is needed only for tail prefixed calls that cannot be dispatched as // fast calls. if (!canFastTailCall) { fgMorphTailCall(call); } // Implementation note : If we optimize tailcall to do a direct jump // to the target function (after stomping on the return address, etc), // without using CORINFO_HELP_TAILCALL, we have to make certain that // we don't starve the hijacking logic (by stomping on the hijacked // return address etc). // At this point, we are committed to do the tailcall. compTailCallUsed = true; CorInfoTailCall tailCallResult; if (fastTailCallToLoop) { tailCallResult = TAILCALL_RECURSIVE; } else if (canFastTailCall) { tailCallResult = TAILCALL_OPTIMIZED; } else { tailCallResult = TAILCALL_HELPER; } // for non user funcs, we have no handles to report info.compCompHnd->reportTailCallDecision(nullptr, (call->gtCallType == CT_USER_FUNC) ? call->gtCallMethHnd : nullptr, isTailPrefixed, tailCallResult, nullptr); // As we will actually call CORINFO_HELP_TAILCALL, set the callTyp to TYP_VOID. // to avoid doing any extra work for the return value. call->gtType = TYP_VOID; #ifdef DEBUG if (verbose) { printf("\nGTF_CALL_M_TAILCALL bit set for call "); printTreeID(call); printf("\n"); if (fastTailCallToLoop) { printf("\nGTF_CALL_M_TAILCALL_TO_LOOP bit set for call "); printTreeID(call); printf("\n"); } } #endif GenTreePtr stmtExpr = fgMorphStmt->gtStmt.gtStmtExpr; bool deleteReturn = false; if (info.compRetBuffArg != BAD_VAR_NUM) { // In this case we simply have a call followed by a return. noway_assert(fgMorphStmt->gtNext->gtStmt.gtStmtExpr->gtOper == GT_RETURN); deleteReturn = true; } else if ((stmtExpr->gtOper == GT_ASG) && (fgMorphStmt->gtNext != nullptr)) { GenTreePtr nextStmtExpr = fgMorphStmt->gtNext->gtStmt.gtStmtExpr; noway_assert(nextStmtExpr->gtOper == GT_RETURN); // In this case we have an assignment of the result of the call, and then a return of the result of the assignment. // This can occur if impSpillStackEnsure() has introduced an assignment to a temp. noway_assert(stmtExpr->gtGetOp1()->OperIsLocal() && nextStmtExpr->OperGet() == GT_RETURN && nextStmtExpr->gtGetOp1() != nullptr && nextStmtExpr->gtGetOp1()->OperIsLocal() && stmtExpr->gtGetOp1()->AsLclVarCommon()->gtLclNum == nextStmtExpr->gtGetOp1()->AsLclVarCommon()->gtLclNum); deleteReturn = true; } if (deleteReturn) { fgRemoveStmt(compCurBB, fgMorphStmt->gtNext); } // For void calls, we would have created a GT_CALL in the stmt list. // For non-void calls, we would have created a GT_RETURN(GT_CAST(GT_CALL)). // For calls returning structs, we would have a void call, followed by a void return. // For debuggable code, it would be an assignment of the call to a temp // We want to get rid of any of this extra trees, and just leave // the call bool tailCallFollowedByPopAndRet = false; GenTreePtr stmt; #ifdef DEBUG noway_assert((stmtExpr->gtOper == GT_CALL && stmtExpr == call) || // Either a call stmt (stmtExpr->gtOper == GT_RETURN && (stmtExpr->gtOp.gtOp1 == call || stmtExpr->gtOp.gtOp1->gtOp.gtOp1 == call)) || // GT_RETURN(GT_CALL(..)) (stmtExpr->gtOper == GT_ASG && stmtExpr->gtOp.gtOp2 == call)); // or var = call #endif #ifdef _TARGET_AMD64_ if ((stmtExpr->gtOper == GT_CALL) && (fgMorphStmt->gtNext != nullptr)) { // We have a stmt node after a tail call node. This must be a tail call occuring // in the following IL pattern // tail.call // pop // ret // Since tail prefix is honored, we can get rid of the remaining two stmts // corresponding to pop and ret. Note that 'pop' may or may not result in // a new statement (see impImportBlockCode() for details). stmt = fgMorphStmt->gtNext; if (stmt->gtNext != nullptr) { // We have a pop tree. // It must be side effect free. GenTreePtr ret = stmt->gtNext; noway_assert((stmt->gtStmt.gtStmtExpr->gtFlags & GTF_ALL_EFFECT) == 0); fgRemoveStmt(compCurBB, stmt); stmt = ret; } noway_assert(stmt->gtStmt.gtStmtExpr->gtOper == GT_RETURN); fgRemoveStmt(compCurBB, stmt); tailCallFollowedByPopAndRet = true; } #else //!TARGET_AMD64_ #ifdef DEBUG noway_assert(fgMorphStmt->gtNext == nullptr); #endif #endif //!_TARGET_AMD64_ fgMorphStmt->gtStmt.gtStmtExpr = call; // Tail call via helper: The VM can't use return address hijacking if we're // not going to return and the helper doesn't have enough info to safely poll, // so we poll before the tail call, if the block isn't already safe. Since // tail call via helper is a slow mechanism it doen't matter whether we emit // GC poll. This is done to be in parity with Jit64. Also this avoids GC info // size increase if all most all methods are expected to be tail calls (e.g. F#). // // Note that we can avoid emitting GC-poll if we know that the current BB is // dominated by a Gc-SafePoint block. But we don't have dominator info at this // point. One option is to just add a place holder node for GC-poll (e.g. GT_GCPOLL) // here and remove it in lowering if the block is dominated by a GC-SafePoint. For // now it not clear whether optimizing slow tail calls is worth the effort. As a // low cost check, we check whether the first and current basic blocks are // GC-SafePoints. // // Fast Tail call as epilog+jmp - No need to insert GC-poll. Instead, fgSetBlockOrder() // is going to mark the method as fully interruptible if the block containing this tail // call is reachable without executing any call. if (canFastTailCall || (fgFirstBB->bbFlags & BBF_GC_SAFE_POINT) || (compCurBB->bbFlags & BBF_GC_SAFE_POINT) || !fgCreateGCPoll(GCPOLL_INLINE, compCurBB)) { // We didn't insert a poll block, so we need to morph the call now // (Normally it will get morphed when we get to the split poll block) GenTreePtr temp = fgMorphCall(call); noway_assert(temp == call); } // Tail call via helper: we just call CORINFO_HELP_TAILCALL, and it jumps to // the target. So we don't need an epilog - just like CORINFO_HELP_THROW. // // Fast tail call: in case of fast tail calls, we need a jmp epilog and // hence mark it as BBJ_RETURN with BBF_JMP flag set. noway_assert(compCurBB->bbJumpKind == BBJ_RETURN); if (canFastTailCall) { compCurBB->bbFlags |= BBF_HAS_JMP; } else { compCurBB->bbJumpKind = BBJ_THROW; } // For non-void calls, we return a place holder which will be // used by the parent GT_RETURN node of this call. This should // not be done for tail calls occuring in the following IL pattern, // since this pattern is supported only in void returning methods. // tail.call // pop // ret GenTree* result = call; if (!tailCallFollowedByPopAndRet && (callType != TYP_VOID) && info.compRetType != TYP_VOID) { #ifdef _TARGET_ARM_ // Return a dummy node, as the return is already removed. if (callType == TYP_STRUCT) { // This is a HFA, use float 0. callType = TYP_FLOAT; } #elif defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) // Return a dummy node, as the return is already removed. if (varTypeIsStruct(callType)) { // This is a register-returned struct. Return a 0. // The actual return registers are hacked in lower and the register allocator. callType = TYP_INT; } #endif #ifdef FEATURE_SIMD // Return a dummy node, as the return is already removed. if (varTypeIsSIMD(callType)) { callType = TYP_DOUBLE; } #endif result = gtNewZeroConNode(genActualType(callType)); result = fgMorphTree(result); } return result; } NO_TAIL_CALL: if ((call->gtCallMoreFlags & GTF_CALL_M_SPECIAL_INTRINSIC) == 0 && (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_VIRTUAL_FUNC_PTR) #ifdef FEATURE_READYTORUN_COMPILER || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_READYTORUN_VIRTUAL_FUNC_PTR) #endif ) && (call == fgMorphStmt->gtStmt.gtStmtExpr)) { // This is call to CORINFO_HELP_VIRTUAL_FUNC_PTR with ignored result. // Transform it into a null check. GenTreePtr thisPtr = call->gtCallArgs->gtOp.gtOp1; GenTreePtr nullCheck = gtNewOperNode(GT_IND, TYP_I_IMPL, thisPtr); nullCheck->gtFlags |= GTF_EXCEPT; return fgMorphTree(nullCheck); } noway_assert(call->gtOper == GT_CALL); // // Only count calls once (only in the global morph phase) // if (fgGlobalMorph) { if (call->gtCallType == CT_INDIRECT) { optCallCount++; optIndirectCallCount++; } else if (call->gtCallType == CT_USER_FUNC) { optCallCount++; if (call->IsVirtual()) optIndirectCallCount++; } } // Couldn't inline - remember that this BB contains method calls // If this is a 'regular' call, mark the basic block as // having a call (for computing full interruptibility). // // Amd64 note: If this is a fast tail call then don't count it as a call // since we don't insert GC-polls but instead make the method fully GC // interruptible. #ifdef _TARGET_AMD64_ if (!call->IsFastTailCall()) #endif { if (call->gtCallType == CT_INDIRECT) { compCurBB->bbFlags |= BBF_GC_SAFE_POINT; } else if (call->gtCallType == CT_USER_FUNC) { if ((call->gtCallMoreFlags & GTF_CALL_M_NOGCCHECK) == 0) compCurBB->bbFlags |= BBF_GC_SAFE_POINT; } // otherwise we have a CT_HELPER } // Morph Type.op_Equality and Type.op_Inequality // We need to do this before the arguments are morphed if ((call->gtCallMoreFlags & GTF_CALL_M_SPECIAL_INTRINSIC)) { CorInfoIntrinsics methodID = info.compCompHnd->getIntrinsicID(call->gtCallMethHnd); genTreeOps simpleOp = GT_CALL; if (methodID == CORINFO_INTRINSIC_TypeEQ) simpleOp = GT_EQ; else if (methodID == CORINFO_INTRINSIC_TypeNEQ) simpleOp = GT_NE; if (simpleOp == GT_EQ || simpleOp == GT_NE) { noway_assert(call->TypeGet() == TYP_INT); // Check for GetClassFromHandle(handle) and obj.GetType() both of which will only return RuntimeType objects. // Then if either operand is one of these two calls we can simplify op_Equality/op_Inequality to GT_NE/GT_NE: // One important invariance that should never change is that type equivalency is always equivalent to object // identity equality for runtime type objects in reflection. This is also reflected in RuntimeTypeHandle::TypeEquals. // If this invariance would ever be broken, we need to remove the optimization below. GenTreePtr op1 = call->gtCallArgs->gtOp.gtOp1; GenTreePtr op2 = call->gtCallArgs->gtOp.gtOp2->gtOp.gtOp1; if (gtCanOptimizeTypeEquality(op1) || gtCanOptimizeTypeEquality(op2)) { GenTreePtr compare = gtNewOperNode(simpleOp, TYP_INT, op1, op2); // fgMorphSmpOp will further optimize the following patterns: // 1. typeof(...) == typeof(...) // 2. typeof(...) == obj.GetType() return fgMorphTree(compare); } } } // Make sure that return buffers containing GC pointers that aren't too large are pointers into the stack. GenTreePtr origDest = NULL; // Will only become non-null if we do the transformation (and thus require copy-back). unsigned retValTmpNum = BAD_VAR_NUM; CORINFO_CLASS_HANDLE structHnd = NULL; if (call->gtCallMoreFlags & GTF_CALL_M_RETBUFFARG && call->gtCallLateArgs == NULL) // Don't do this if we're re-morphing (which will make late args non-null). { // We're enforcing the invariant that return buffers pointers (at least for // struct return types containing GC pointers) are never pointers into the heap. // The large majority of cases are address of local variables, which are OK. // Otherwise, allocate a local of the given struct type, pass its address, // then assign from that into the proper destination. (We don't need to do this // if we're passing the caller's ret buff arg to the callee, since the caller's caller // will maintain the same invariant.) GenTreePtr dest = call->gtCallArgs->gtOp.gtOp1; assert(dest->OperGet() != GT_ARGPLACE); // If it was, we'd be in a remorph, which we've already excluded above. if (dest->gtType == TYP_BYREF && !(dest->OperGet() == GT_ADDR && dest->gtOp.gtOp1->OperGet() == GT_LCL_VAR)) { // We'll exempt helper calls from this, assuming that the helper implementation // follows the old convention, and does whatever barrier is required. if (call->gtCallType != CT_HELPER) { structHnd = call->gtRetClsHnd; if (info.compCompHnd->isStructRequiringStackAllocRetBuf(structHnd) && !((dest->OperGet() == GT_LCL_VAR || dest->OperGet() == GT_REG_VAR) && dest->gtLclVar.gtLclNum == info.compRetBuffArg)) { origDest = dest; retValTmpNum = lvaGrabTemp(true DEBUGARG("substitute local for ret buff arg")); lvaSetStruct(retValTmpNum, structHnd, true); dest = gtNewOperNode(GT_ADDR, TYP_BYREF, gtNewLclvNode(retValTmpNum, TYP_STRUCT)); } } } call->gtCallArgs->gtOp.gtOp1 = dest; } /* Process the "normal" argument list */ call = fgMorphArgs(call); // Optimize get_ManagedThreadId(get_CurrentThread) noway_assert(call->gtOper == GT_CALL); // Morph stelem.ref helper call to store a null value, into a store into an array without the helper. // This needs to be done after the arguments are morphed to ensure constant propagation has already taken place. if ((call->gtCallType == CT_HELPER) && (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ARRADDR_ST))) { GenTreePtr value = gtArgEntryByArgNum(call, 2)->node; if (value->OperGet() == GT_CNS_INT && value->AsIntConCommon()->IconValue() == 0) { GenTreePtr arr = gtArgEntryByArgNum(call, 0)->node; GenTreePtr index = gtArgEntryByArgNum(call, 1)->node; arr = gtClone(arr, true); if (arr != nullptr) { index = gtClone(index, true); if (index != nullptr) { value = gtClone(value); noway_assert(value != nullptr); GenTreePtr nullCheckedArr = impCheckForNullPointer(arr); GenTreePtr arrIndexNode = gtNewIndexRef(TYP_REF, nullCheckedArr, index); GenTreePtr arrStore = gtNewAssignNode(arrIndexNode, value); arrStore->gtFlags |= GTF_ASG; return fgMorphTree(arrStore); } } } } if ((call->gtCallMoreFlags & GTF_CALL_M_SPECIAL_INTRINSIC) && info.compCompHnd->getIntrinsicID(call->gtCallMethHnd) == CORINFO_INTRINSIC_GetManagedThreadId) { noway_assert(origDest == NULL); noway_assert(call->gtCallLateArgs->gtOp.gtOp1 != NULL); GenTreePtr innerCall = call->gtCallLateArgs->gtOp.gtOp1; if (innerCall->gtOper == GT_CALL && (innerCall->gtCall.gtCallMoreFlags & GTF_CALL_M_SPECIAL_INTRINSIC) && info.compCompHnd->getIntrinsicID(innerCall->gtCall.gtCallMethHnd) == CORINFO_INTRINSIC_GetCurrentManagedThread) { // substitute expression with call to helper GenTreePtr newCall = gtNewHelperCallNode(CORINFO_HELP_GETCURRENTMANAGEDTHREADID, TYP_INT, 0); JITDUMP("get_ManagedThreadId(get_CurrentThread) folding performed\n"); return fgMorphTree(newCall); } } if (origDest != NULL) { GenTreePtr retValVarAddr = gtNewOperNode(GT_ADDR, TYP_BYREF, gtNewLclvNode(retValTmpNum, TYP_STRUCT)); // If the origDest expression was an assignment to a variable, it might be to an otherwise-unused // var, which would allow the whole assignment to be optimized away to a NOP. So in that case, make the // origDest into a comma that uses the var. Note that the var doesn't have to be a temp for this to // be correct. if (origDest->OperGet() == GT_ASG) { if (origDest->gtOp.gtOp1->OperGet() == GT_LCL_VAR) { GenTreePtr var = origDest->gtOp.gtOp1; origDest = gtNewOperNode(GT_COMMA, var->TypeGet(), origDest, gtNewLclvNode(var->gtLclVar.gtLclNum, var->TypeGet())); } } GenTreePtr copyBlk = gtNewCpObjNode(origDest, retValVarAddr, structHnd, false); copyBlk = fgMorphTree(copyBlk); GenTree* result = gtNewOperNode(GT_COMMA, TYP_VOID, call, copyBlk); #ifdef DEBUG result->gtFlags |= GTF_MORPHED; #endif return result; } return call; } /***************************************************************************** * * Transform the given GTK_CONST tree for code generation. */ GenTreePtr Compiler::fgMorphConst(GenTreePtr tree) { noway_assert(tree->OperKind() & GTK_CONST); /* Clear any exception flags or other unnecessary flags * that may have been set before folding this node to a constant */ tree->gtFlags &= ~(GTF_ALL_EFFECT | GTF_REVERSE_OPS); if (tree->OperGet() != GT_CNS_STR) return tree; // TODO-CQ: Do this for compCurBB->isRunRarely(). Doing that currently will // guarantee slow performance for that block. Instead cache the return value // of CORINFO_HELP_STRCNS and go to cache first giving reasonable perf. if (compCurBB->bbJumpKind == BBJ_THROW) { CorInfoHelpFunc helper = info.compCompHnd->getLazyStringLiteralHelper(tree->gtStrCon.gtScpHnd); if (helper != CORINFO_HELP_UNDEF) { // For un-important blocks, we want to construct the string lazily GenTreeArgList *args; if (helper == CORINFO_HELP_STRCNS_CURRENT_MODULE) { args = gtNewArgList(gtNewIconNode(RidFromToken(tree->gtStrCon.gtSconCPX), TYP_INT)); } else { args = gtNewArgList(gtNewIconNode(RidFromToken(tree->gtStrCon.gtSconCPX), TYP_INT), gtNewIconEmbScpHndNode(tree->gtStrCon.gtScpHnd)); } tree = gtNewHelperCallNode(helper, TYP_REF, 0, args); return fgMorphTree(tree); } } assert(tree->gtStrCon.gtScpHnd == info.compScopeHnd || !IsUninitialized(tree->gtStrCon.gtScpHnd)); LPVOID pValue; InfoAccessType iat = info.compCompHnd->constructStringLiteral(tree->gtStrCon.gtScpHnd, tree->gtStrCon.gtSconCPX, &pValue); tree = gtNewStringLiteralNode(iat, pValue); return fgMorphTree(tree); } /***************************************************************************** * * Transform the given GTK_LEAF tree for code generation. */ GenTreePtr Compiler::fgMorphLeaf(GenTreePtr tree) { noway_assert(tree->OperKind() & GTK_LEAF); if (tree->gtOper == GT_LCL_VAR) { return fgMorphLocalVar(tree); } #ifdef _TARGET_X86_ else if (tree->gtOper == GT_LCL_FLD) { if (info.compIsVarArgs) { GenTreePtr newTree = fgMorphStackArgForVarArgs(tree->gtLclFld.gtLclNum, tree->gtType, tree->gtLclFld.gtLclOffs); if (newTree != NULL) return newTree; } } #endif // _TARGET_X86_ else if (tree->gtOper == GT_FTN_ADDR) { CORINFO_CONST_LOOKUP addrInfo; #ifdef FEATURE_READYTORUN_COMPILER if (tree->gtFptrVal.gtEntryPoint.addr != nullptr) { addrInfo = tree->gtFptrVal.gtEntryPoint; } else #endif { info.compCompHnd->getFunctionFixedEntryPoint(tree->gtFptrVal.gtFptrMethod, &addrInfo); } // Refer to gtNewIconHandleNode() as the template for constructing a constant handle // tree->SetOper(GT_CNS_INT); tree->gtIntConCommon.SetIconValue(ssize_t(addrInfo.handle)); tree->gtFlags |= GTF_ICON_FTN_ADDR; switch (addrInfo.accessType) { case IAT_PPVALUE: tree = gtNewOperNode(GT_IND, TYP_I_IMPL, tree); tree->gtFlags |= GTF_IND_INVARIANT; __fallthrough; case IAT_PVALUE: tree = gtNewOperNode(GT_IND, TYP_I_IMPL, tree); break; case IAT_VALUE: tree = gtNewOperNode(GT_NOP, tree->TypeGet(), tree); // prevents constant folding break; default: noway_assert(!"Unknown addrInfo.accessType"); } return fgMorphTree(tree); } return tree; } void Compiler::fgAssignSetVarDef(GenTreePtr tree) { GenTreeLclVarCommon* lclVarCmnTree; bool isEntire = false; if (tree->DefinesLocal(this, &lclVarCmnTree, &isEntire)) { if (isEntire) { lclVarCmnTree->gtFlags |= GTF_VAR_DEF; } else { // We consider partial definitions to be modeled as uses followed by definitions. // This captures the idea that precedings defs are not necessarily made redundant // by this definition. lclVarCmnTree->gtFlags |= (GTF_VAR_DEF | GTF_VAR_USEASG); } } } GenTreePtr Compiler::fgMorphOneAsgBlockOp(GenTreePtr tree) { genTreeOps oper = tree->gtOper; // Only xxBlk opcodes are possible noway_assert(tree->OperIsBlkOp()); GenTreePtr dest = tree->gtOp.gtOp1->gtOp.gtOp1; // Dest address GenTreePtr src = tree->gtOp.gtOp1->gtOp.gtOp2; // Src GenTreePtr blkShape = tree->gtOp.gtOp2; // [size/clsHnd] bool volatil = tree->AsBlkOp()->IsVolatile(); GenTreePtr result; GenTreePtr lclVarTree; // The dest must be an address noway_assert(genActualType(dest->gtType) == TYP_I_IMPL || dest->gtType == TYP_BYREF); // For COPYBLK the src must be an address noway_assert(!tree->OperIsCopyBlkOp() || (genActualType( src->gtType) == TYP_I_IMPL || src->gtType == TYP_BYREF)); // For INITBLK the src must be a TYP_INT noway_assert(oper != GT_INITBLK || (genActualType( src->gtType) == TYP_INT)); // The size must be an integer type noway_assert(varTypeIsIntegral(blkShape->gtType)); CORINFO_CLASS_HANDLE clsHnd; size_t size; var_types type = TYP_UNDEF; if (blkShape->gtOper != GT_CNS_INT) goto GENERAL_BLKOP; #ifdef FEATURE_SIMD // importer introduces cpblk nodes with src = GT_ADDR(GT_SIMD) // The SIMD type in question could be Vector2f which is 8-bytes in size. // The below check is to make sure that we don't turn that copyblk // into a assignment, since rationalizer logic will transform the // copyblk apropriately. Otherwise, the transormation made in this // routine will prevent rationalizer logic and we might end up with // GT_ADDR(GT_SIMD) node post rationalization, leading to a noway assert // in codegen. if (src->OperGet() == GT_ADDR && src->gtGetOp1()->OperGet() == GT_SIMD) goto GENERAL_BLKOP; #endif if (!blkShape->IsIconHandle()) { clsHnd = 0; size = blkShape->gtIntCon.gtIconVal; /* A four byte BLK_COPY can be treated as an integer asignment */ if (size == 4) type = TYP_INT; #ifdef _TARGET_64BIT_ if (size == 8) type = TYP_LONG; #endif } else { clsHnd = (CORINFO_CLASS_HANDLE) blkShape->gtIntCon.gtIconVal; size = roundUp(info.compCompHnd->getClassSize(clsHnd), sizeof(void*)); // Since we round up, we are not handling the case where we have a // non-dword sized struct with GC pointers. // The EE currently does not allow this, but we may change. Lets assert it // just to be safe. noway_assert(info.compCompHnd->getClassSize(clsHnd) == size); if (size == REGSIZE_BYTES) { BYTE gcPtr; info.compCompHnd->getClassGClayout(clsHnd, &gcPtr); type = getJitGCType(gcPtr); } } // // See if we can do a simple transformation: // // GT_ASG <TYP_size> // / \ // GT_IND GT_IND or CNS_INT // | | // [dest] [src] // switch (size) { case 1: type = TYP_BYTE; goto ONE_SIMPLE_ASG; case 2: type = TYP_SHORT; goto ONE_SIMPLE_ASG; #ifdef _TARGET_64BIT_ case 4: type = TYP_INT; goto ONE_SIMPLE_ASG; #endif // _TARGET_64BIT_ case REGSIZE_BYTES: noway_assert(type != TYP_UNDEF); ONE_SIMPLE_ASG: noway_assert(size <= REGSIZE_BYTES); // For INITBLK, a non constant source is not going to allow us to fiddle // with the bits to create a single assigment. if ((oper == GT_INITBLK) && (src->gtOper != GT_CNS_INT)) { goto GENERAL_BLKOP; } if (impIsAddressInLocal(dest, &lclVarTree)) { #if LOCAL_ASSERTION_PROP // Kill everything about dest if (optLocalAssertionProp) { if (optAssertionCount > 0) { fgKillDependentAssertions(lclVarTree->gtLclVarCommon.gtLclNum DEBUGARG(tree)); } } #endif // LOCAL_ASSERTION_PROP unsigned lclNum = lclVarTree->gtLclVarCommon.gtLclNum; // A previous incarnation of this code also required the local not to be // address-exposed(=taken). That seems orthogonal to the decision of whether // to do field-wise assignments: being address-exposed will cause it to be // "dependently" promoted, so it will be in the right memory location. One possible // further reason for avoiding field-wise stores is that the struct might have alignment-induced // holes, whose contents could be meaningful in unsafe code. If we decide that's a valid // concern, then we could compromise, and say that address-exposed + fields do not completely cover the memory // of the struct prevent field-wise assignments. Same situation exists for the "src" decision. if (varTypeIsStruct(lclVarTree) && (lvaTable[lclNum].lvPromoted || lclVarIsSIMDType(lclNum))) { // Let fgMorphInitBlock handle it. (Since we'll need to do field-var-wise assignments.) goto GENERAL_BLKOP; } else if (!varTypeIsFloating(lclVarTree->TypeGet()) && size == genTypeSize(var_types(lvaTable[lclNum].lvType))) { // Use the dest local var directly. dest = lclVarTree; type = lvaTable[lclNum].lvType; // Make the type used in the GT_IND node match // If the block operation had been a write to a local var of a small int type, // of the exact size of the small int type, and the var is NormalizeOnStore, // we would have labeled it GTF_VAR_USEASG, because the block operation wouldn't // have done that normalization. If we're now making it into an assignment, // the NormalizeOnStore will work, and it can be a full def. if (lvaTable[lclNum].lvNormalizeOnStore()) { dest->gtFlags &= (~GTF_VAR_USEASG); } goto _DoneDest; } else { // Could be a non-promoted struct, or a floating point type local, or // an int subject to a partial write. Don't enregister. lvaSetVarDoNotEnregister(lclNum DEBUG_ARG(DNER_LocalField)); // Fall through to indirect the dest node. } // Mark the local var tree as a definition point of the local. lclVarTree->gtFlags |= GTF_VAR_DEF; if (size < lvaTable[lclNum].lvExactSize) // If it's not a full-width assignment.... lclVarTree->gtFlags |= GTF_VAR_USEASG; } // Check to ensure we are not creating a reducible *(& ... ) if (dest->gtOper == GT_ADDR) { GenTreePtr addrOp = dest->gtOp.gtOp1; // Ignore reinterpret casts between int/gc if ((addrOp->TypeGet() == type) || (varTypeIsIntegralOrI(addrOp) && (genTypeSize(addrOp->TypeGet()) == size))) { dest = addrOp; type = addrOp->TypeGet(); goto _DoneDest; } } /* Indirect the dest node */ dest = gtNewOperNode(GT_IND, type, dest); /* As long as we don't have more information about the destination we have to assume it could live anywhere (not just in the GC heap). Mark the GT_IND node so that we use the correct write barrier helper in case the field is a GC ref. */ dest->gtFlags |= (GTF_EXCEPT | GTF_GLOB_REF | GTF_IND_TGTANYWHERE); _DoneDest:; if (volatil) dest->gtFlags |= GTF_DONT_CSE; if (tree->OperIsCopyBlkOp()) { if (impIsAddressInLocal(src, &lclVarTree)) { unsigned lclNum = lclVarTree->gtLclVarCommon.gtLclNum; if (varTypeIsStruct(lclVarTree) && (lvaTable[lclNum].lvPromoted || lclVarIsSIMDType(lclNum))) { // Let fgMorphCopyBlock handle it. goto GENERAL_BLKOP; } else if (!varTypeIsFloating(lclVarTree->TypeGet()) && size == genTypeSize(genActualType(lclVarTree->TypeGet()))) { /* Use the src local var directly */ src = lclVarTree; goto _DoneSrc; } else { #ifndef LEGACY_BACKEND // The source argument of the copyblk can potentially // be accessed only through indir(addr(lclVar)) // or indir(lclVarAddr) in rational form and liveness // won't account for these uses. That said, // we have to mark this local as address exposed so // we don't delete it as a dead store later on. unsigned lclVarNum = lclVarTree->gtLclVarCommon.gtLclNum; lvaTable[lclVarNum].lvAddrExposed = true; lvaSetVarDoNotEnregister(lclVarNum DEBUG_ARG(DNER_AddrExposed)); #else // LEGACY_BACKEND lvaSetVarDoNotEnregister(lclVarTree->gtLclVarCommon.gtLclNum DEBUG_ARG(DNER_LocalField)); #endif // LEGACY_BACKEND // Fall through to indirect the src node. } } /* Indirect the src node */ src = gtNewOperNode(GT_IND, type, src); src->gtFlags |= (GTF_EXCEPT | GTF_GLOB_REF | GTF_IND_TGTANYWHERE); _DoneSrc:; if (volatil) src->gtFlags |= GTF_DONT_CSE; } else // (oper == GT_INITBLK) { if (size > 1) { size_t cns = src->gtIntCon.gtIconVal; cns = cns & 0xFF; cns |= cns << 8; if (size >= 4) { cns |= cns << 16; #ifdef _TARGET_64BIT_ if (size == 8) { cns |= cns << 32; } #endif // _TARGET_64BIT_ src->gtType = type; // Make the type used in the GT_IND node match for TYP_REF // if we are using an GT_INITBLK on a GC type the value being assigned has to be zero (null) assert(!varTypeIsGC(type) || (cns == 0)); } src->gtIntCon.gtIconVal = cns; } } /* Create the assignment node */ result = gtNewAssignNode(dest, src); result->gtType = type; return result; } GENERAL_BLKOP: return nullptr; } //------------------------------------------------------------------------ // fgMorphInitBlock: Perform the Morphing of a GT_INITBLK node // // Arguments: // tree - a tree node with a gtOper of GT_INITBLK // the child nodes for tree have already been Morphed // // Return Value: // We can return the orginal GT_INITBLK unmodified (least desirable, but always correct) // We can return a single assignment, when fgMorphOneAsgBlockOp transforms it (most desirable) // If we have performed struct promotion of the Dest() then we will try to // perform a field by field assignment for each of the promoted struct fields // // Notes: // If we leave it as a GT_INITBLK we will call lvaSetVarDoNotEnregister() with a reason of DNER_BlockOp // if the Dest() is a a struct that has a "CustomLayout" and "ConstainsHoles" then we // can not use a field by field assignment and must the orginal GT_INITBLK unmodified. GenTreePtr Compiler::fgMorphInitBlock(GenTreePtr tree) { noway_assert(tree->gtOper == GT_INITBLK); JITDUMP("\nfgMorphInitBlock:"); GenTreePtr oneAsgTree = fgMorphOneAsgBlockOp(tree); if (oneAsgTree) { JITDUMP(" using oneAsgTree.\n"); tree = oneAsgTree; } else { GenTreeInitBlk* initBlkOp = tree->AsInitBlk(); GenTreePtr destAddr = initBlkOp->Dest(); GenTreePtr initVal = initBlkOp->InitVal(); GenTreePtr blockSize = initBlkOp->Size(); // The dest must be an address noway_assert(genActualType(destAddr->gtType) == TYP_I_IMPL || destAddr->gtType == TYP_BYREF); // The size must be an integer type assert(varTypeIsIntegral(blockSize->gtType)); unsigned blockWidth = 0; bool blockWidthIsConst = false; if (blockSize->IsCnsIntOrI()) { blockWidthIsConst = true; blockWidth = unsigned(blockSize->gtIntConCommon.IconValue()); } GenTreeLclVarCommon* lclVarTree = nullptr; FieldSeqNode* destFldSeq = nullptr; unsigned destLclNum = BAD_VAR_NUM; LclVarDsc * destLclVar = nullptr; bool destDoFldAsg = false; if (destAddr->IsLocalAddrExpr(this, &lclVarTree, &destFldSeq)) { destLclNum = lclVarTree->gtLclNum; destLclVar = &lvaTable[destLclNum]; #if LOCAL_ASSERTION_PROP // Kill everything about destLclNum (and its field locals) if (optLocalAssertionProp) { if (optAssertionCount > 0) { fgKillDependentAssertions(destLclNum DEBUGARG(tree)); } } #endif // LOCAL_ASSERTION_PROP if (destLclVar->lvPromoted && blockWidthIsConst) { noway_assert(varTypeIsStruct(destLclVar)); noway_assert(!opts.MinOpts()); if (destLclVar->lvAddrExposed & destLclVar->lvContainsHoles) { JITDUMP(" dest is address exposed"); } else { if (blockWidth == destLclVar->lvExactSize) { JITDUMP(" (destDoFldAsg=true)"); // We may decide later that a copyblk is required when this struct has holes destDoFldAsg = true; } else { JITDUMP(" with mismatched size"); } } } } // Can we use field by field assignment for the dest? if (destDoFldAsg && destLclVar->lvCustomLayout && destLclVar->lvContainsHoles) { JITDUMP(" dest contains holes"); destDoFldAsg = false; } JITDUMP(destDoFldAsg ? " using field by field initialization.\n" : " this requires an InitBlock.\n"); if (!destDoFldAsg && (destLclVar != nullptr)) { // If destLclVar is not a reg-sized non-field-addressed struct, set it as DoNotEnregister. if (!destLclVar->lvRegStruct) { // Mark it as DoNotEnregister. lvaSetVarDoNotEnregister(destLclNum DEBUG_ARG(DNER_BlockOp)); } } // Mark the dest struct as DoNotEnreg // when they are LclVar structs and we are using a CopyBlock // or the struct is not promoted // if (!destDoFldAsg) { #if CPU_USES_BLOCK_MOVE compBlkOpUsed = true; #endif goto _Done; } // The initVal must be a constant of TYP_INT noway_assert(initVal->OperGet() == GT_CNS_INT); noway_assert(genActualType(initVal->gtType) == TYP_INT); // The dest must be of a struct type. noway_assert(varTypeIsStruct(destLclVar)); // // Now, convert InitBlock to individual assignments // tree = nullptr; GenTreePtr asg; GenTreePtr dest; GenTreePtr srcCopy; unsigned fieldLclNum; unsigned fieldCnt = destLclVar->lvFieldCnt; for (unsigned i=0; i<fieldCnt; ++i) { fieldLclNum = destLclVar->lvFieldLclStart + i; dest = gtNewLclvNode(fieldLclNum, lvaTable[fieldLclNum].TypeGet()); noway_assert(destAddr->gtOp.gtOp1->gtOper == GT_LCL_VAR); // If it had been labeled a "USEASG", assignments to the the individual promoted fields are not. dest->gtFlags |= destAddr->gtOp.gtOp1->gtFlags & ~(GTF_NODE_MASK | GTF_VAR_USEASG); srcCopy = gtCloneExpr(initVal); noway_assert(srcCopy != nullptr); // need type of oper to be same as tree if (dest->gtType == TYP_LONG) { srcCopy->ChangeOperConst(GT_CNS_NATIVELONG); // copy and extend the value srcCopy->gtIntConCommon.SetLngValue(initVal->gtIntConCommon.IconValue()); /* Change the types of srcCopy to TYP_LONG */ srcCopy->gtType = TYP_LONG; } else if (varTypeIsFloating(dest->gtType)) { srcCopy->ChangeOperConst(GT_CNS_DBL); // setup the bit pattern memset(&srcCopy->gtDblCon.gtDconVal, (int)initVal->gtIntCon.gtIconVal, sizeof(srcCopy->gtDblCon.gtDconVal)); /* Change the types of srcCopy to TYP_DOUBLE */ srcCopy->gtType = TYP_DOUBLE; } else { noway_assert(srcCopy->gtOper == GT_CNS_INT); noway_assert(srcCopy->TypeGet() == TYP_INT); // setup the bit pattern memset(&srcCopy->gtIntCon.gtIconVal, (int)initVal->gtIntCon.gtIconVal, sizeof(srcCopy->gtIntCon.gtIconVal)); } srcCopy->gtType = dest->TypeGet(); asg = gtNewAssignNode(dest, srcCopy); #if LOCAL_ASSERTION_PROP if (optLocalAssertionProp) { optAssertionGen(asg); } #endif // LOCAL_ASSERTION_PROP if (tree) { tree = gtNewOperNode(GT_COMMA, TYP_VOID, tree, asg); } else { tree = asg; } } } #ifdef DEBUG tree->gtFlags |= GTF_MORPHED; if (verbose) { printf("fgMorphInitBlock (after):\n"); gtDispTree(tree); } #endif _Done: return tree; } //------------------------------------------------------------------------ // fgMorphCopyBlock: Perform the Morphing of a GT_COPYBLK and GT_COPYOBJ nodes // // Arguments: // tree - a tree node with a gtOper of GT_COPYBLK or GT_COPYOBJ // the child nodes for tree have already been Morphed // // Return Value: // We can return the orginal GT_COPYBLK or GT_COPYOBJ unmodified (least desirable, but always correct) // We can return a single assignment, when fgMorphOneAsgBlockOp transforms it (most desirable) // If we have performed struct promotion of the Source() or the Dest() then we will try to // perform a field by field assignment for each of the promoted struct fields // // Notes: // If we leave it as a GT_COPYBLK or GT_COPYOBJ we will call lvaSetVarDoNotEnregister() on both Source() and Dest() // When performing a field by field assignment we can have one of Source() or Dest treated as a blob of bytes // and in such cases we will call lvaSetVarDoNotEnregister() on the one treated as a blob of bytes. // if the Source() or Dest() is a a struct that has a "CustomLayout" and "ConstainsHoles" then we // can not use a field by field assignment and must the orginal GT_COPYBLK unmodified. GenTreePtr Compiler::fgMorphCopyBlock(GenTreePtr tree) { noway_assert(tree->OperIsCopyBlkOp()); JITDUMP("\nfgMorphCopyBlock:"); bool isLateArg = (tree->gtFlags & GTF_LATE_ARG) != 0; GenTreePtr oneAsgTree = fgMorphOneAsgBlockOp(tree); if (oneAsgTree) { JITDUMP(" using oneAsgTree.\n"); tree = oneAsgTree; } else { GenTreePtr destAddr; GenTreePtr srcAddr; GenTreePtr blockSize; bool isCopyObj; if (tree->OperGet() == GT_COPYBLK) { GenTreeCpBlk* copyBlkOp = tree->AsCpBlk(); isCopyObj = false; destAddr = copyBlkOp->Dest(); srcAddr = copyBlkOp->Source(); blockSize = copyBlkOp->Size(); } else { GenTreeCpObj* copyObjOp = tree->AsCpObj(); isCopyObj = true; destAddr = copyObjOp->Dest(); srcAddr = copyObjOp->Source(); blockSize = copyObjOp->ClsTok(); } noway_assert(destAddr->TypeGet() == TYP_BYREF || destAddr->TypeGet() == TYP_I_IMPL); noway_assert(srcAddr->TypeGet() == TYP_BYREF || srcAddr->TypeGet() == TYP_I_IMPL); unsigned blockWidth = 0; bool blockWidthIsConst = false; if (blockSize->IsCnsIntOrI()) { blockWidthIsConst = true; if (blockSize->IsIconHandle(GTF_ICON_CLASS_HDL)) { CORINFO_CLASS_HANDLE clsHnd = (CORINFO_CLASS_HANDLE) blockSize->gtIntConCommon.IconValue(); blockWidth = info.compCompHnd->getClassSize(clsHnd); } else { blockWidth = unsigned(blockSize->gtIntConCommon.IconValue()); } } GenTreeLclVarCommon* lclVarTree = nullptr; FieldSeqNode* destFldSeq = nullptr; unsigned destLclNum = BAD_VAR_NUM; LclVarDsc* destLclVar = nullptr; bool destDoFldAsg = false; bool destOnStack = false; if (destAddr->IsLocalAddrExpr(this, &lclVarTree, &destFldSeq)) { destOnStack = true; destLclNum = lclVarTree->gtLclNum; destLclVar = &lvaTable[destLclNum]; #if LOCAL_ASSERTION_PROP // Kill everything about destLclNum (and its field locals) if (optLocalAssertionProp) { if (optAssertionCount > 0) { fgKillDependentAssertions(destLclNum DEBUGARG(tree)); } } #endif // LOCAL_ASSERTION_PROP if (destLclVar->lvPromoted && blockWidthIsConst) { noway_assert(varTypeIsStruct(destLclVar)); noway_assert(!opts.MinOpts()); if (blockWidth == destLclVar->lvExactSize) { JITDUMP(" (destDoFldAsg=true)"); // We may decide later that a copyblk is required when this struct has holes destDoFldAsg = true; } else { JITDUMP(" with mismatched dest size"); } } } FieldSeqNode* srcFldSeq = nullptr; unsigned srcLclNum = BAD_VAR_NUM; LclVarDsc* srcLclVar = nullptr; bool srcDoFldAsg = false; if (srcAddr->IsLocalAddrExpr(this, &lclVarTree, &srcFldSeq)) { srcLclNum = lclVarTree->gtLclNum; srcLclVar = &lvaTable[srcLclNum]; if (srcLclVar->lvPromoted && blockWidthIsConst) { noway_assert(varTypeIsStruct(srcLclVar)); noway_assert(!opts.MinOpts()); if (blockWidth == srcLclVar->lvExactSize) { JITDUMP(" (srcDoFldAsg=true)"); // We may decide later that a copyblk is required when this struct has holes srcDoFldAsg = true; } else { JITDUMP(" with mismatched src size"); } } } // Check to see if we are required to do a copy block because the struct contains holes // and either the src or dest is externally visible // bool requiresCopyBlock = false; bool srcSingleLclVarAsg = false; // If either src or dest is a reg-sized non-field-addressed struct, keep the copyBlock. if ((destLclVar != nullptr && destLclVar->lvRegStruct) || (srcLclVar != nullptr && srcLclVar->lvRegStruct)) { requiresCopyBlock = true; } // Can we use field by field assignment for the dest? if (destDoFldAsg && destLclVar->lvCustomLayout && destLclVar->lvContainsHoles) { JITDUMP(" dest contains custom layout and contains holes"); // C++ style CopyBlock with holes requiresCopyBlock = true; } // Can we use field by field assignment for the src? if (srcDoFldAsg && srcLclVar->lvCustomLayout && srcLclVar->lvContainsHoles) { JITDUMP(" src contains custom layout and contains holes"); // C++ style CopyBlock with holes requiresCopyBlock = true; } if (tree->OperGet() == GT_COPYBLK && tree->AsCpBlk()->gtBlkOpGcUnsafe) { requiresCopyBlock = true; } // If we passed the above checks, then we will check these two if (!requiresCopyBlock) { // Are both dest and src promoted structs? if (destDoFldAsg && srcDoFldAsg) { // Both structs should be of the same type, if not we will use a copy block if (lvaTable[destLclNum].lvVerTypeInfo.GetClassHandle() != lvaTable[srcLclNum].lvVerTypeInfo.GetClassHandle()) { requiresCopyBlock = true; // Mismatched types, leave as a CopyBlock JITDUMP(" with mismatched types"); } } // Are neither dest or src promoted structs? else if (!destDoFldAsg && !srcDoFldAsg) { requiresCopyBlock = true; // Leave as a CopyBlock JITDUMP(" with no promoted structs"); } else if (destDoFldAsg) { // Match the following kinds of trees: // fgMorphTree BB01, stmt 9 (before) // [000052] ------------ const int 8 // [000053] -A--G------- copyBlk void // [000051] ------------ addr byref // [000050] ------------ lclVar long V07 loc5 // [000054] --------R--- <list> void // [000049] ------------ addr byref // [000048] ------------ lclVar struct(P) V06 loc4 // long V06.h (offs=0x00) -> V17 tmp9 // Yields this transformation // fgMorphCopyBlock (after): // [000050] ------------ lclVar long V07 loc5 // [000085] -A---------- = long // [000083] D------N---- lclVar long V17 tmp9 // if (blockWidthIsConst && (destLclVar->lvFieldCnt == 1) && (srcLclVar != nullptr) && (blockWidth == genTypeSize(srcLclVar->TypeGet()))) { // Reject the following tree: // - seen on x86chk jit\jit64\hfa\main\hfa_sf3E_r.exe // // fgMorphTree BB01, stmt 6 (before) // [000038] ------------- const int 4 // [000039] -A--G-------- copyBlk void // [000037] ------------- addr byref // [000036] ------------- lclVar int V05 loc3 // [000040] --------R---- <list> void // [000035] ------------- addr byref // [000034] ------------- lclVar struct(P) V04 loc2 // float V04.f1 (offs=0x00) -> V13 tmp6 // As this would framsform into // float V13 = int V05 // unsigned fieldLclNum = lvaTable[destLclNum].lvFieldLclStart; var_types destType = lvaTable[fieldLclNum].TypeGet(); if (srcLclVar->TypeGet() == destType) { srcSingleLclVarAsg = true; } } } } // If we require a copy block the set both of the field assign bools to false if (requiresCopyBlock) { // If a copy block is required then we won't do field by field assignments destDoFldAsg = false; srcDoFldAsg = false; } JITDUMP(requiresCopyBlock ? " this requires a CopyBlock.\n" : " using field by field assignments.\n"); // Mark the dest/src structs as DoNotEnreg // when they are not reg-sized non-field-addressed structs and we are using a CopyBlock // or the struct is not promoted // if (!destDoFldAsg && (destLclVar != nullptr)) { if (!destLclVar->lvRegStruct) { // Mark it as DoNotEnregister. lvaSetVarDoNotEnregister(destLclNum DEBUG_ARG(DNER_BlockOp)); } } if (!srcDoFldAsg && (srcLclVar != nullptr) && !srcSingleLclVarAsg) { if (!srcLclVar->lvRegStruct) { lvaSetVarDoNotEnregister(srcLclNum DEBUG_ARG(DNER_BlockOp)); } } if (requiresCopyBlock) { #if CPU_USES_BLOCK_MOVE compBlkOpUsed = true; #endif // Note that the unrolling of CopyBlk is only implemented on some platforms // Currently that includes x64 and Arm64 but not x64 or Arm32 #ifdef CPBLK_UNROLL_LIMIT // If we have a CopyObj with a dest on the stack // we will convert it into an GC Unsafe CopyBlk that is non-interruptible // when its size is small enouch to be completely unrolled (i.e. between [16..64] bytes) // if (isCopyObj && destOnStack && blockWidthIsConst && (blockWidth >= (2*TARGET_POINTER_SIZE)) && (blockWidth <= CPBLK_UNROLL_LIMIT)) { tree->SetOper(GT_COPYBLK); tree->AsCpBlk()->gtBlkOpGcUnsafe = true; // Mark as a GC unsage copy block blockSize->gtIntConCommon.SetIconValue(ssize_t(blockWidth)); blockSize->gtFlags &= ~GTF_ICON_HDL_MASK; // Clear the GTF_ICON_CLASS_HDL flags } #endif // Liveness doesn't consider copyblk arguments of simple types as being // a use or def, so explicitly mark these variables as address-exposed. if (srcLclNum != BAD_VAR_NUM && !varTypeIsStruct(srcLclVar)) { JITDUMP("Non-struct copyBlk src V%02d is addr exposed\n", srcLclNum); lvaTable[srcLclNum].lvAddrExposed = true; } if (destLclNum != BAD_VAR_NUM && !varTypeIsStruct(destLclVar)) { JITDUMP("Non-struct copyBlk dest V%02d is addr exposed\n", destLclNum); lvaTable[destLclNum].lvAddrExposed = true; } goto _Done; } // // Otherwise we convert this CopyBlock into individual field by field assignments // tree = nullptr; GenTreePtr asg; GenTreePtr dest; GenTreePtr src; GenTreePtr addrSpill = nullptr; unsigned addrSpillTemp = BAD_VAR_NUM; bool addrSpillIsStackDest = false; // true if 'addrSpill' represents the address in our local stack frame unsigned fieldCnt = DUMMY_INIT(0); if (destDoFldAsg && srcDoFldAsg) { // To do fieldwise assignments for both sides, they'd better be the same struct type! // All of these conditions were checked above... assert(destLclNum != BAD_VAR_NUM && srcLclNum != BAD_VAR_NUM); assert(lvaTable[destLclNum].lvVerTypeInfo.GetClassHandle() == lvaTable[srcLclNum].lvVerTypeInfo.GetClassHandle()); assert(destLclVar != nullptr && srcLclVar != nullptr && destLclVar->lvFieldCnt == srcLclVar->lvFieldCnt); fieldCnt = destLclVar->lvFieldCnt; goto _AssignFields; // No need to spill the address to the temp. Go ahead to morph it into field assignments. } else if (destDoFldAsg) { fieldCnt = destLclVar->lvFieldCnt; } else { assert(srcDoFldAsg); fieldCnt = srcLclVar->lvFieldCnt; } if (destDoFldAsg) { noway_assert(!srcDoFldAsg); if (gtClone(srcAddr)) { // srcAddr is simple expression. No need to spill. noway_assert((srcAddr->gtFlags & GTF_PERSISTENT_SIDE_EFFECTS) == 0); } else { // srcAddr is complex expression. Clone and spill it (unless the destination is // a struct local that only has one field, in which case we'd only use the // address value once...) if (destLclVar->lvFieldCnt > 1) { addrSpill = gtCloneExpr(srcAddr); // addrSpill represents the 'srcAddr' noway_assert(addrSpill != nullptr); } } } if (srcDoFldAsg) { noway_assert(!destDoFldAsg); // If we're doing field-wise stores, to an address within a local, and we copy // the address into "addrSpill", do *not* declare the original local var node in the // field address as GTF_VAR_DEF and GTF_VAR_USEASG; we will declare each of the // field-wise assignments as an "indirect" assignment to the local. // ("lclVarTree" is a subtree of "destAddr"; make sure we remove the flags before // we clone it.) if (lclVarTree != nullptr) { lclVarTree->gtFlags &= ~(GTF_VAR_DEF | GTF_VAR_USEASG); } if (gtClone(destAddr)) { // destAddr is simple expression. No need to spill noway_assert((destAddr->gtFlags & GTF_PERSISTENT_SIDE_EFFECTS) == 0); } else { // destAddr is complex expression. Clone and spill it (unless // the source is a struct local that only has one field, in which case we'd only // use the address value once...) if (srcLclVar->lvFieldCnt > 1) { addrSpill = gtCloneExpr(destAddr); // addrSpill represents the 'destAddr' noway_assert(addrSpill != nullptr); } // TODO-CQ: this should be based on a more general // "BaseAddress" method, that handles fields of structs, before or after // morphing. if (addrSpill != nullptr && addrSpill->OperGet() == GT_ADDR) { if (addrSpill->gtOp.gtOp1->IsLocal()) { // We will *not* consider this to define the local, but rather have each individual field assign // be a definition. addrSpill->gtOp.gtOp1->gtFlags &= ~(GTF_LIVENESS_MASK); assert(lvaTable[addrSpill->gtOp.gtOp1->gtLclVarCommon.gtLclNum].lvLclBlockOpAddr == 1); addrSpillIsStackDest = true; // addrSpill represents the address of LclVar[varNum] in our local stack frame } } } } if (addrSpill != nullptr) { // Spill the (complex) address to a BYREF temp. // Note, at most one address may need to be spilled. addrSpillTemp = lvaGrabTemp(true DEBUGARG("BlockOp address local")); #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING lvaTable[addrSpillTemp].lvType = TYP_I_IMPL; tree = gtNewAssignNode(gtNewLclvNode(addrSpillTemp, TYP_I_IMPL), addrSpill); #else // !FEATURE_UNIX_AMD64_STRUCT_PASSING lvaTable[addrSpillTemp].lvType = TYP_BYREF; if (addrSpillIsStackDest) { lvaTable[addrSpillTemp].lvStackByref = true; } tree = gtNewAssignNode(gtNewLclvNode(addrSpillTemp, TYP_BYREF), addrSpill); #endif // !FEATURE_UNIX_AMD64_STRUCT_PASSING #ifndef LEGACY_BACKEND // If we are assigning the address of a LclVar here // liveness does not account for this kind of address taken use. // // We have to mark this local as address exposed so // that we don't delete the definition for this LclVar // as a dead store later on. // if (addrSpill->OperGet() == GT_ADDR) { GenTreePtr addrOp = addrSpill->gtOp.gtOp1; if (addrOp->IsLocal()) { unsigned lclVarNum = addrOp->gtLclVarCommon.gtLclNum; lvaTable[lclVarNum].lvAddrExposed = true; lvaSetVarDoNotEnregister(lclVarNum DEBUG_ARG(DNER_AddrExposed)); } } #endif // !LEGACY_BACKEND } _AssignFields: for (unsigned i=0; i<fieldCnt; ++i) { FieldSeqNode* curFieldSeq = nullptr; if (destDoFldAsg) { noway_assert(destLclNum != BAD_VAR_NUM); unsigned fieldLclNum = lvaTable[destLclNum].lvFieldLclStart + i; dest = gtNewLclvNode(fieldLclNum, lvaTable[fieldLclNum].TypeGet()); noway_assert(destAddr->gtOp.gtOp1->gtOper == GT_LCL_VAR); // If it had been labeled a "USEASG", assignments to the the individual promoted fields are not. dest->gtFlags |= destAddr->gtOp.gtOp1->gtFlags & ~(GTF_NODE_MASK | GTF_VAR_USEASG); } else { noway_assert(srcDoFldAsg); noway_assert(srcLclNum != BAD_VAR_NUM); unsigned fieldLclNum = lvaTable[srcLclNum].lvFieldLclStart + i; if (addrSpill) { assert(addrSpillTemp != BAD_VAR_NUM); dest = gtNewLclvNode(addrSpillTemp, TYP_BYREF); } else { dest = gtCloneExpr(destAddr); noway_assert(dest != nullptr); // Is the address of a local? GenTreeLclVarCommon* lclVarTree = nullptr; bool isEntire = false; bool* pIsEntire = (blockWidthIsConst ? &isEntire : nullptr); if (dest->DefinesLocalAddr(this, blockWidth, &lclVarTree, pIsEntire)) { lclVarTree->gtFlags |= GTF_VAR_DEF; if (!isEntire) lclVarTree->gtFlags |= GTF_VAR_USEASG; } } GenTreePtr fieldOffsetNode = gtNewIconNode(lvaTable[fieldLclNum].lvFldOffset, TYP_I_IMPL); // Have to set the field sequence -- which means we need the field handle. CORINFO_CLASS_HANDLE classHnd = lvaTable[srcLclNum].lvVerTypeInfo.GetClassHandle(); CORINFO_FIELD_HANDLE fieldHnd = info.compCompHnd->getFieldInClass(classHnd, lvaTable[fieldLclNum].lvFldOrdinal); curFieldSeq = GetFieldSeqStore()->CreateSingleton(fieldHnd); fieldOffsetNode->gtIntCon.gtFieldSeq = curFieldSeq; dest = gtNewOperNode(GT_ADD, TYP_BYREF, dest, fieldOffsetNode); dest = gtNewOperNode(GT_IND, lvaTable[fieldLclNum].TypeGet(), dest); // !!! The destination could be on stack. !!! // This flag will let us choose the correct write barrier. dest->gtFlags |= GTF_IND_TGTANYWHERE; } if (srcDoFldAsg) { noway_assert(srcLclNum != BAD_VAR_NUM); unsigned fieldLclNum = lvaTable[srcLclNum].lvFieldLclStart + i; src = gtNewLclvNode(fieldLclNum, lvaTable[fieldLclNum].TypeGet()); noway_assert(srcAddr->gtOp.gtOp1->gtOper == GT_LCL_VAR); src->gtFlags |= srcAddr->gtOp.gtOp1->gtFlags & ~GTF_NODE_MASK; } else { noway_assert(destDoFldAsg); noway_assert(destLclNum != BAD_VAR_NUM); unsigned fieldLclNum = lvaTable[destLclNum].lvFieldLclStart + i; if (srcSingleLclVarAsg) { noway_assert(fieldCnt == 1); noway_assert(srcLclVar != nullptr); noway_assert(addrSpill == nullptr); src = gtNewLclvNode(srcLclNum, srcLclVar->TypeGet()); } else { if (addrSpill) { assert(addrSpillTemp != BAD_VAR_NUM); src = gtNewLclvNode(addrSpillTemp, TYP_BYREF); } else { src = gtCloneExpr(srcAddr); noway_assert(src != nullptr); } CORINFO_CLASS_HANDLE classHnd = lvaTable[destLclNum].lvVerTypeInfo.GetClassHandle(); CORINFO_FIELD_HANDLE fieldHnd = info.compCompHnd->getFieldInClass(classHnd, lvaTable[fieldLclNum].lvFldOrdinal); curFieldSeq = GetFieldSeqStore()->CreateSingleton(fieldHnd); src = gtNewOperNode(GT_ADD, TYP_BYREF, src, new(this, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, lvaTable[fieldLclNum].lvFldOffset, curFieldSeq)); src = gtNewOperNode(GT_IND, lvaTable[fieldLclNum].TypeGet(), src); } } noway_assert(dest->TypeGet() == src->TypeGet()); asg = gtNewAssignNode(dest, src); // If we spilled the address, and we didn't do individual field assignments to promoted fields, // and it was of a local, record the assignment as an indirect update of a local. if (addrSpill && !destDoFldAsg && destLclNum != BAD_VAR_NUM) { curFieldSeq = GetFieldSeqStore()->Append(destFldSeq, curFieldSeq); bool isEntire = (genTypeSize(var_types(lvaTable[destLclNum].lvType)) == genTypeSize(dest->TypeGet())); IndirectAssignmentAnnotation* pIndirAnnot = new (this, CMK_Unknown) IndirectAssignmentAnnotation(destLclNum, curFieldSeq, isEntire); GetIndirAssignMap()->Set(asg, pIndirAnnot); } #if LOCAL_ASSERTION_PROP if (optLocalAssertionProp) { optAssertionGen(asg); } #endif // LOCAL_ASSERTION_PROP if (tree) { tree = gtNewOperNode(GT_COMMA, TYP_VOID, tree, asg); } else { tree = asg; } } } if (isLateArg) { tree->gtFlags |= GTF_LATE_ARG; } #ifdef DEBUG tree->gtFlags |= GTF_MORPHED; if (verbose) { printf("\nfgMorphCopyBlock (after):\n"); gtDispTree(tree); } #endif _Done: return tree; } // insert conversions and normalize to make tree amenable to register // FP architectures GenTree* Compiler::fgMorphForRegisterFP(GenTree *tree) { GenTreePtr op1 = tree->gtOp.gtOp1; GenTreePtr op2 = tree->gtGetOp2(); if (tree->OperIsArithmetic() && varTypeIsFloating(tree)) { if (op1->TypeGet() != tree->TypeGet()) { tree->gtOp.gtOp1 = gtNewCastNode(tree->TypeGet(), tree->gtOp.gtOp1, tree->TypeGet()); } if (op2->TypeGet() != tree->TypeGet()) { tree->gtOp.gtOp2 = gtNewCastNode(tree->TypeGet(), tree->gtOp.gtOp2, tree->TypeGet()); } } else if (tree->OperIsCompare() && varTypeIsFloating(op1) && op1->TypeGet() != op2->TypeGet()) { // both had better be floating, just one bigger than other assert (varTypeIsFloating(op2)); if (op1->TypeGet() == TYP_FLOAT) { tree->gtOp.gtOp1 = gtNewCastNode(TYP_DOUBLE, tree->gtOp.gtOp1, TYP_DOUBLE); } else if (op2->TypeGet() == TYP_FLOAT) { tree->gtOp.gtOp2 = gtNewCastNode(TYP_DOUBLE, tree->gtOp.gtOp2, TYP_DOUBLE); } } return tree; } GenTree* Compiler::fgMorphRecognizeBoxNullable(GenTree* compare) { GenTree* op1 = compare->gtOp.gtOp1; GenTree* op2 = compare->gtOp.gtOp2; GenTree* opCns; GenTreeCall* opCall; // recognize this pattern: // // stmtExpr void (IL 0x000... ???) // return int // const ref null // == int // call help ref HELPER.CORINFO_HELP_BOX_NULLABLE // const(h) long 0x7fed96836c8 class // addr byref // ld.lclVar struct V00 arg0 // // // which comes from this code (reported by customer as being slow) : // // private static bool IsNull<T>(T arg) // { // return arg==null; // } // if (op1->IsCnsIntOrI() && op2->IsHelperCall()) { opCns = op1; opCall = op2->AsCall(); } else if (op1->IsHelperCall() && op2->IsCnsIntOrI()) { opCns = op2; opCall = op1->AsCall(); } else { return compare; } if (opCns->gtIntConCommon.IconValue() != 0) return compare; if (eeGetHelperNum(opCall->gtCallMethHnd) != CORINFO_HELP_BOX_NULLABLE) return compare; // replace the box with an access of the nullable 'hasValue' field which is at the zero offset GenTree* newOp = gtNewOperNode(GT_IND, TYP_BOOL, opCall->gtCall.gtCallArgs->gtOp.gtOp2->gtOp.gtOp1); if (opCall == op1) compare->gtOp.gtOp1 = newOp; else compare->gtOp.gtOp2 = newOp; return compare; } #ifdef FEATURE_SIMD //-------------------------------------------------------------------------------------- // fgCopySIMDNode: make a copy of a SIMD intrinsic node, e.g. so that a field can be accessed. // // Arguments: // simdNode - The GenTreeSIMD node to be copied // // Return Value: // A comma node where op1 is the assignment of the simd node to a temp, and op2 is the temp lclVar. // GenTree* Compiler::fgCopySIMDNode(GenTreeSIMD* simdNode) { // Copy the result of the SIMD intrinsic into a temp. unsigned lclNum = lvaGrabTemp(true DEBUGARG("Copy of SIMD intrinsic with field access")); CORINFO_CLASS_HANDLE simdHandle = NO_CLASS_HANDLE; // We only have fields of the fixed float vectors. noway_assert(simdNode->gtSIMDBaseType == TYP_FLOAT); switch(simdNode->gtSIMDSize) { case 8: simdHandle = SIMDVector2Handle; break; case 12: simdHandle = SIMDVector3Handle; break; case 16: simdHandle = SIMDVector4Handle; break; default: noway_assert(!"field of unexpected SIMD type"); break; } assert(simdHandle != NO_CLASS_HANDLE); lvaSetStruct(lclNum, simdHandle, false, true); lvaTable[lclNum].lvFieldAccessed = true; GenTree* asg = gtNewTempAssign(lclNum, simdNode); GenTree* newLclVarNode = new (this, GT_LCL_VAR) GenTreeLclVar(simdNode->TypeGet(), lclNum, BAD_IL_OFFSET); GenTree* comma = gtNewOperNode(GT_COMMA, simdNode->TypeGet(), asg, newLclVarNode); return comma; } //-------------------------------------------------------------------------------------------------------------- // getSIMDStructFromField: // Checking whether the field belongs to a simd struct or not. If it is, return the GenTreePtr for // the struct node, also base type, field index and simd size. If it is not, just return nullptr. // Usually if the tree node is from a simd lclvar which is not used in any SIMD intrinsic, then we // should return nullptr, since in this case we should treat SIMD struct as a regular struct. // However if no matter what, you just want get simd struct node, you can set the ignoreUsedInSIMDIntrinsic // as true. Then there will be no IsUsedInSIMDIntrinsic checking, and it will return SIMD struct node // if the struct is a SIMD struct. // // Arguments: // tree - GentreePtr. This node will be checked to see this is a field which belongs to a simd // struct used for simd intrinsic or not. // pBaseTypeOut - var_types pointer, if the tree node is the tree we want, we set *pBaseTypeOut // to simd lclvar's base type. // indexOut - unsigned pointer, if the tree is used for simd intrinsic, we will set *indexOut // equals to the index number of this field. // simdSizeOut - unsigned pointer, if the tree is used for simd intrinsic, set the *simdSizeOut // equals to the simd struct size which this tree belongs to. // ignoreUsedInSIMDIntrinsic - bool. If this is set to true, then this function will ignore // the UsedInSIMDIntrinsic check. // // return value: // A GenTreePtr which points the simd lclvar tree belongs to. If the tree is not the simd // instrinic related field, return nullptr. // GenTreePtr Compiler::getSIMDStructFromField(GenTreePtr tree, var_types* pBaseTypeOut, unsigned* indexOut, unsigned* simdSizeOut, bool ignoreUsedInSIMDIntrinsic/*false*/) { GenTreePtr ret = nullptr; if(tree->OperGet() == GT_FIELD) { GenTreePtr objRef = tree->gtField.gtFldObj; if (objRef != nullptr) { GenTreePtr obj = nullptr; if (objRef->gtOper == GT_ADDR) { obj = objRef->gtOp.gtOp1; } else if(ignoreUsedInSIMDIntrinsic) { obj = objRef; } else { return nullptr; } if (isSIMDTypeLocal(obj)) { unsigned lclNum = obj->gtLclVarCommon.gtLclNum; LclVarDsc* varDsc = &lvaTable[lclNum]; if(varDsc->lvIsUsedInSIMDIntrinsic() || ignoreUsedInSIMDIntrinsic) { *simdSizeOut = varDsc->lvExactSize; *pBaseTypeOut = getBaseTypeOfSIMDLocal(obj); ret = obj; } } else if (obj->OperGet() == GT_SIMD) { ret = obj; GenTreeSIMD* simdNode = obj->AsSIMD(); *simdSizeOut = simdNode->gtSIMDSize; *pBaseTypeOut = simdNode->gtSIMDBaseType; } } } if (ret != nullptr) { unsigned BaseTypeSize = genTypeSize(*pBaseTypeOut); *indexOut = tree->gtField.gtFldOffset / BaseTypeSize; } return ret; } /***************************************************************************** * If a read operation tries to access simd struct field, then transform the this * operation to to the SIMD intrinsic SIMDIntrinsicGetItem, and return the new tree. * Otherwise, return the old tree. * Argument: * tree - GenTreePtr. If this pointer points to simd struct which is used for simd * intrinsic. We will morph it as simd intrinsic SIMDIntrinsicGetItem. * Return: * A GenTreePtr which points to the new tree. If the tree is not for simd intrinsic, * return nullptr. */ GenTreePtr Compiler::fgMorphFieldToSIMDIntrinsicGet(GenTreePtr tree) { unsigned index = 0; var_types baseType = TYP_UNKNOWN; unsigned simdSize = 0; GenTreePtr simdStructNode = getSIMDStructFromField(tree, &baseType, &index, &simdSize); if(simdStructNode != nullptr) { assert(simdSize >= ((index + 1) * genTypeSize(baseType))); GenTree* op2 = gtNewIconNode(index); tree = gtNewSIMDNode(baseType, simdStructNode, op2, SIMDIntrinsicGetItem, baseType, simdSize); #ifdef DEBUG tree->gtFlags |= GTF_MORPHED; #endif } return tree; } /***************************************************************************** * Transform an assignment of a SIMD struct field to SIMD intrinsic * SIMDIntrinsicGetItem, and return a new tree. If If it is not such an assignment, * then return the old tree. * Argument: * tree - GenTreePtr. If this pointer points to simd struct which is used for simd * intrinsic. We will morph it as simd intrinsic set. * Return: * A GenTreePtr which points to the new tree. If the tree is not for simd intrinsic, * return nullptr. */ GenTreePtr Compiler::fgMorphFieldAssignToSIMDIntrinsicSet(GenTreePtr tree) { assert(tree->OperGet() == GT_ASG); GenTreePtr op1 = tree->gtGetOp1(); GenTreePtr op2 = tree->gtGetOp2(); unsigned index = 0; var_types baseType = TYP_UNKNOWN; unsigned simdSize = 0; GenTreePtr simdOp1Struct = getSIMDStructFromField(op1, &baseType, &index, &simdSize); if (simdOp1Struct != nullptr) { //Generate the simd set intrinsic assert(simdSize >= ((index + 1) * genTypeSize(baseType))); SIMDIntrinsicID simdIntrinsicID = SIMDIntrinsicInvalid; switch (index) { case 0: simdIntrinsicID = SIMDIntrinsicSetX; break; case 1: simdIntrinsicID = SIMDIntrinsicSetY; break; case 2: simdIntrinsicID = SIMDIntrinsicSetZ; break; case 3: simdIntrinsicID = SIMDIntrinsicSetW; break; default: noway_assert("There is no set intrinsic for index bigger than 3"); } GenTreePtr newStruct = gtClone(simdOp1Struct); assert((newStruct != nullptr) && (varTypeIsSIMD(newStruct))); GenTreePtr simdTree = gtNewSIMDNode(newStruct->gtType, simdOp1Struct, op2, simdIntrinsicID, baseType, simdSize); GenTreePtr copyBlkDst = gtNewOperNode(GT_ADDR, TYP_BYREF, newStruct); tree = gtNewBlkOpNode(GT_COPYBLK, copyBlkDst, gtNewOperNode(GT_ADDR, TYP_BYREF, simdTree), gtNewIconNode(simdSize), false); #ifdef DEBUG tree->gtFlags |= GTF_MORPHED; #endif } return tree; } #endif /***************************************************************************** * * Transform the given GTK_SMPOP tree for code generation. */ #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:21000) // Suppress PREFast warning about overly large function #endif GenTreePtr Compiler::fgMorphSmpOp(GenTreePtr tree, MorphAddrContext* mac) { // this extra scope is a workaround for a gcc bug // the inline destructor for ALLOCA_CHECK confuses the control // flow and gcc thinks that the function never returns { ALLOCA_CHECK(); noway_assert(tree->OperKind() & GTK_SMPOP); /* The steps in this function are : o Perform required preorder processing o Process the first, then second operand, if any o Perform required postorder morphing o Perform optional postorder morphing if optimizing */ bool isQmarkColon = false; #if LOCAL_ASSERTION_PROP AssertionIndex origAssertionCount = DUMMY_INIT(0); AssertionDsc * origAssertionTab = DUMMY_INIT(NULL); AssertionIndex thenAssertionCount = DUMMY_INIT(0); AssertionDsc * thenAssertionTab = DUMMY_INIT(NULL); #endif if (fgGlobalMorph) { #if !FEATURE_STACK_FP_X87 tree = fgMorphForRegisterFP(tree); #endif } genTreeOps oper = tree->OperGet(); var_types typ = tree->TypeGet(); GenTreePtr op1 = tree->gtOp.gtOp1; GenTreePtr op2 = tree->gtGetOp2(); /*------------------------------------------------------------------------- * First do any PRE-ORDER processing */ switch (oper) { // Some arithmetic operators need to use a helper call to the EE int helper; case GT_ASG: tree = fgDoNormalizeOnStore(tree); /* fgDoNormalizeOnStore can change op2 */ noway_assert(op1 == tree->gtOp.gtOp1); op2 = tree->gtOp.gtOp2; #ifdef FEATURE_SIMD { // We should check whether op2 should be assigned to a SIMD field or not. // if it is, we should tranlate the tree to simd intrinsic GenTreePtr newTree = fgMorphFieldAssignToSIMDIntrinsicSet(tree); if (newTree != tree) { tree = newTree; oper = tree->OperGet(); typ = tree->TypeGet(); op1 = tree->gtOp.gtOp1; op2 = tree->gtGetOp2(); } } #endif __fallthrough; case GT_ASG_ADD: case GT_ASG_SUB: case GT_ASG_MUL: case GT_ASG_DIV: case GT_ASG_MOD: case GT_ASG_UDIV: case GT_ASG_UMOD: case GT_ASG_OR: case GT_ASG_XOR: case GT_ASG_AND: case GT_ASG_LSH: case GT_ASG_RSH: case GT_ASG_RSZ: case GT_CHS: /* We can't CSE the LHS of an assignment. Only r-values can be CSEed */ op1->gtFlags |= GTF_DONT_CSE; break; case GT_ADDR: /* op1 of a GT_ADDR is an l-value. Only r-values can be CSEed */ op1->gtFlags |= GTF_DONT_CSE; break; case GT_QMARK: case GT_JTRUE: noway_assert(op1); if (op1->OperKind() & GTK_RELOP) { noway_assert((oper == GT_JTRUE) || (op1->gtFlags & GTF_RELOP_QMARK)); /* Mark the comparison node with GTF_RELOP_JMP_USED so it knows that it does not need to materialize the result as a 0 or 1. */ /* We also mark it as DONT_CSE, as we don't handle QMARKs with nonRELOP op1s */ op1->gtFlags |= (GTF_RELOP_JMP_USED | GTF_DONT_CSE); // Request that the codegen for op1 sets the condition flags // when it generates the code for op1. // // Codegen for op1 must set the condition flags if // this method returns true. // op1->gtRequestSetFlags(); } else { GenTreePtr effOp1 = op1->gtEffectiveVal(); noway_assert( (effOp1->gtOper == GT_CNS_INT) && ((effOp1->gtIntCon.gtIconVal == 0) || (effOp1->gtIntCon.gtIconVal == 1)) ); } break; case GT_COLON: #if LOCAL_ASSERTION_PROP if (optLocalAssertionProp) #endif isQmarkColon = true; break; case GT_INDEX: return fgMorphArrayIndex(tree); case GT_CAST: return fgMorphCast(tree); case GT_MUL: #ifndef _TARGET_64BIT_ #if !LONG_MATH_REGPARAM if (typ == TYP_LONG) { /* For (long)int1 * (long)int2, we dont actually do the casts, and just multiply the 32 bit values, which will give us the 64 bit result in edx:eax */ noway_assert(op2); if ((op1->gtOper == GT_CAST && op2->gtOper == GT_CAST && genActualType(op1->CastFromType()) == TYP_INT && genActualType(op2->CastFromType()) == TYP_INT)&& !op1->gtOverflow() && !op2->gtOverflow()) { // The casts have to be of the same signedness. if ((op1->gtFlags & GTF_UNSIGNED) != (op2->gtFlags & GTF_UNSIGNED)) { //We see if we can force an int constant to change its signedness GenTreePtr constOp; if (op1->gtCast.CastOp()->gtOper == GT_CNS_INT) constOp = op1; else if (op2->gtCast.CastOp()->gtOper == GT_CNS_INT) constOp = op2; else goto NO_MUL_64RSLT; if ( ((unsigned)(constOp->gtCast.CastOp()->gtIntCon.gtIconVal) < (unsigned)(0x80000000)) ) constOp->gtFlags ^= GTF_UNSIGNED; else goto NO_MUL_64RSLT; } // The only combination that can overflow if (tree->gtOverflow() && (tree->gtFlags & GTF_UNSIGNED) && !( op1->gtFlags & GTF_UNSIGNED)) goto NO_MUL_64RSLT; /* Remaining combinations can never overflow during long mul. */ tree->gtFlags &= ~GTF_OVERFLOW; /* Do unsigned mul only if the casts were unsigned */ tree->gtFlags &= ~GTF_UNSIGNED; tree->gtFlags |= op1->gtFlags & GTF_UNSIGNED; /* Since we are committing to GTF_MUL_64RSLT, we don't want the casts to be folded away. So morph the castees directly */ op1->gtOp.gtOp1 = fgMorphTree(op1->gtOp.gtOp1); op2->gtOp.gtOp1 = fgMorphTree(op2->gtOp.gtOp1); // Propagate side effect flags up the tree op1->gtFlags &= ~GTF_ALL_EFFECT; op1->gtFlags |= (op1->gtOp.gtOp1->gtFlags & GTF_ALL_EFFECT); op2->gtFlags &= ~GTF_ALL_EFFECT; op2->gtFlags |= (op2->gtOp.gtOp1->gtFlags & GTF_ALL_EFFECT); // If the GT_MUL can be altogether folded away, we should do that. if ((op1->gtCast.CastOp()->OperKind() & op2->gtCast.CastOp()->OperKind() & GTK_CONST) && opts.OptEnabled(CLFLG_CONSTANTFOLD)) { tree->gtOp.gtOp1 = op1 = gtFoldExprConst(op1); tree->gtOp.gtOp2 = op2 = gtFoldExprConst(op2); noway_assert(op1->OperKind() & op2->OperKind() & GTK_CONST); tree = gtFoldExprConst(tree); noway_assert(tree->OperIsConst()); return tree; } tree->gtFlags |= GTF_MUL_64RSLT; // If op1 and op2 are unsigned casts, we need to do an unsigned mult tree->gtFlags |= (op1->gtFlags & GTF_UNSIGNED); // Insert GT_NOP nodes for the cast operands so that they do not get folded // And propagate the new flags. We don't want to CSE the casts because // codegen expects GTF_MUL_64RSLT muls to have a certain layout. if (op1->gtCast.CastOp()->OperGet() != GT_NOP) { op1->gtOp.gtOp1 = gtNewOperNode(GT_NOP, TYP_INT, op1->gtCast.CastOp()); op1->gtFlags &= ~GTF_ALL_EFFECT; op1->gtFlags |= (op1->gtCast.CastOp()->gtFlags & GTF_ALL_EFFECT); op1->gtFlags |= GTF_DONT_CSE; } if (op2->gtCast.CastOp()->OperGet() != GT_NOP) { op2->gtOp.gtOp1 = gtNewOperNode(GT_NOP, TYP_INT, op2->gtCast.CastOp()); op2->gtFlags &= ~GTF_ALL_EFFECT; op2->gtFlags |= (op2->gtCast.CastOp()->gtFlags & GTF_ALL_EFFECT); op2->gtFlags |= GTF_DONT_CSE; } tree->gtFlags &= ~GTF_ALL_EFFECT; tree->gtFlags |= ((op1->gtFlags | op2->gtFlags) & GTF_ALL_EFFECT); goto DONE_MORPHING_CHILDREN; } else if ((tree->gtFlags & GTF_MUL_64RSLT) == 0) { NO_MUL_64RSLT: if (tree->gtOverflow()) helper = (tree->gtFlags & GTF_UNSIGNED) ? CORINFO_HELP_ULMUL_OVF : CORINFO_HELP_LMUL_OVF; else helper = CORINFO_HELP_LMUL; goto USE_HELPER_FOR_ARITH; } else { /* We are seeing this node again. We have decided to use GTF_MUL_64RSLT, so leave it alone. */ assert(tree->gtIsValid64RsltMul()); } } #endif // !LONG_MATH_REGPARAM #endif // !_TARGET_64BIT_ break; case GT_DIV: #ifndef _TARGET_64BIT_ #if !LONG_MATH_REGPARAM if (typ == TYP_LONG) { helper = CORINFO_HELP_LDIV; goto USE_HELPER_FOR_ARITH; } #endif #if USE_HELPERS_FOR_INT_DIV if (typ == TYP_INT && !fgIsSignedDivOptimizable(op2)) { helper = CORINFO_HELP_DIV; goto USE_HELPER_FOR_ARITH; } #endif #endif // !_TARGET_64BIT_ #ifndef LEGACY_BACKEND if (op2->gtOper == GT_CAST && op2->gtOp.gtOp1->IsCnsIntOrI()) { op2 = gtFoldExprConst(op2); } if (fgShouldUseMagicNumberDivide(tree->AsOp())) { tree = fgMorphDivByConst(tree->AsOp()); op1 = tree->gtOp.gtOp1; op2 = tree->gtOp.gtOp2; } #endif // !LEGACY_BACKEND break; case GT_UDIV: #ifndef _TARGET_64BIT_ #if !LONG_MATH_REGPARAM if (typ == TYP_LONG) { helper = CORINFO_HELP_ULDIV; goto USE_HELPER_FOR_ARITH; } #endif #if USE_HELPERS_FOR_INT_DIV if (typ == TYP_INT && !fgIsUnsignedDivOptimizable(op2)) { helper = CORINFO_HELP_UDIV; goto USE_HELPER_FOR_ARITH; } #endif #endif // _TARGET_64BIT_ break; case GT_MOD: if (varTypeIsFloating(typ)) { helper = CORINFO_HELP_DBLREM; noway_assert(op2); if (op1->TypeGet() == TYP_FLOAT) if (op2->TypeGet() == TYP_FLOAT) helper = CORINFO_HELP_FLTREM; else tree->gtOp.gtOp1 = op1 = gtNewCastNode(TYP_DOUBLE, op1, TYP_DOUBLE); else if (op2->TypeGet() == TYP_FLOAT) tree->gtOp.gtOp2 = op2 = gtNewCastNode(TYP_DOUBLE, op2, TYP_DOUBLE); goto USE_HELPER_FOR_ARITH; } // Do not use optimizations (unlike UMOD's idiv optimizing during codegen) for signed mod. // A similar optimization for signed mod will not work for a negative perfectly divisible // HI-word. To make it correct, we would need to divide without the sign and then flip the // result sign after mod. This requires 18 opcodes + flow making it not worthy to inline. goto ASSIGN_HELPER_FOR_MOD; case GT_UMOD: #ifdef _TARGET_ARMARCH_ // // Note for _TARGET_ARMARCH_ we don't have a remainder instruction, so we don't do this optimization // #else // _TARGET_XARCH /* If this is an unsigned long mod with op2 which is a cast to long from a constant int, then don't morph to a call to the helper. This can be done faster inline using idiv. */ noway_assert(op2); if ((typ == TYP_LONG) && opts.OptEnabled(CLFLG_CONSTANTFOLD) && ((tree->gtFlags & GTF_UNSIGNED) == (op1->gtFlags & GTF_UNSIGNED)) && ((tree->gtFlags & GTF_UNSIGNED) == (op2->gtFlags & GTF_UNSIGNED))) { if (op2->gtOper == GT_CAST && op2->gtCast.CastOp()->gtOper == GT_CNS_INT && op2->gtCast.CastOp()->gtIntCon.gtIconVal >= 2 && op2->gtCast.CastOp()->gtIntCon.gtIconVal <= 0x3fffffff && (tree->gtFlags & GTF_UNSIGNED) == (op2->gtCast.CastOp()->gtFlags & GTF_UNSIGNED)) { tree->gtOp.gtOp2 = op2 = fgMorphCast(op2); noway_assert(op2->gtOper == GT_CNS_NATIVELONG); } if (op2->gtOper == GT_CNS_NATIVELONG && op2->gtIntConCommon.LngValue() >= 2 && op2->gtIntConCommon.LngValue() <= 0x3fffffff) { tree->gtOp.gtOp1 = op1 = fgMorphTree(op1); noway_assert(op1->TypeGet() == TYP_LONG); // Update flags for op1 morph tree->gtFlags &= ~GTF_ALL_EFFECT; tree->gtFlags |= (op1->gtFlags & GTF_ALL_EFFECT); // Only update with op1 as op2 is a constant // If op1 is a constant, then do constant folding of the division operator if (op1->gtOper == GT_CNS_NATIVELONG) { tree = gtFoldExpr(tree); } return tree; } } #endif // _TARGET_XARCH ASSIGN_HELPER_FOR_MOD: // For "val % 1", return 0 if op1 doesn't have any side effects // and we are not in the CSE phase, we cannot discard 'tree' // because it may contain CSE expressions that we haven't yet examined. // if (((op1->gtFlags & GTF_SIDE_EFFECT) == 0) && !optValnumCSE_phase) { if (((op2->gtOper == GT_CNS_INT) && (op2->gtIntConCommon.IconValue() == 1)) || ((op2->gtOper == GT_CNS_LNG) && (op2->gtIntConCommon.LngValue() == 1))) { GenTreePtr zeroNode = new(this, GT_CNS_INT) GenTreeIntCon(typ, 0); #ifdef DEBUG zeroNode->gtFlags |= GTF_MORPHED; #endif DEBUG_DESTROY_NODE(tree); return zeroNode; } } #ifndef _TARGET_64BIT_ #if !LONG_MATH_REGPARAM if (typ == TYP_LONG) { helper = (oper == GT_UMOD) ? CORINFO_HELP_ULMOD : CORINFO_HELP_LMOD; goto USE_HELPER_FOR_ARITH; } #endif #if USE_HELPERS_FOR_INT_DIV if (typ == TYP_INT) { if (oper == GT_UMOD && !fgIsUnsignedModOptimizable(op2)) { helper = CORINFO_HELP_UMOD; goto USE_HELPER_FOR_ARITH; } else if (oper == GT_MOD && !fgIsSignedModOptimizable(op2)) { helper = CORINFO_HELP_MOD; goto USE_HELPER_FOR_ARITH; } } #endif #endif // !_TARGET_64BIT_ #ifndef LEGACY_BACKEND if (op2->gtOper == GT_CAST && op2->gtOp.gtOp1->IsCnsIntOrI()) { op2 = gtFoldExprConst(op2); } #ifdef _TARGET_ARM64_ // For ARM64 we don't have a remainder instruction, // The architecture manual suggests the following transformation to // generate code for such operator: // // a % b = a - (a / b) * b; // tree = fgMorphModToSubMulDiv(tree->AsOp()); op1 = tree->gtOp.gtOp1; op2 = tree->gtOp.gtOp2; #else // !_TARGET_ARM64_ if (oper != GT_UMOD && fgShouldUseMagicNumberDivide(tree->AsOp())) { tree = fgMorphModByConst(tree->AsOp()); op1 = tree->gtOp.gtOp1; op2 = tree->gtOp.gtOp2; } #endif //_TARGET_ARM64_ #endif // !LEGACY_BACKEND break; USE_HELPER_FOR_ARITH: { /* We have to morph these arithmetic operations into helper calls before morphing the arguments (preorder), else the arguments won't get correct values of fgPtrArgCntCur. However, try to fold the tree first in case we end up with a simple node which won't need a helper call at all */ noway_assert(tree->OperIsBinary()); GenTreePtr oldTree = tree; tree = gtFoldExpr(tree); // Were we able to fold it ? // Note that gtFoldExpr may return a non-leaf even if successful // e.g. for something like "expr / 1" - see also bug #290853 if (tree->OperIsLeaf() || (oldTree != tree)) { return (oldTree != tree) ? fgMorphTree(tree) : fgMorphLeaf(tree); } // Did we fold it into a comma node with throw? if (tree->gtOper == GT_COMMA) { noway_assert(fgIsCommaThrow(tree)); return fgMorphTree(tree); } } return fgMorphIntoHelperCall(tree, helper, gtNewArgList(op1, op2)); case GT_RETURN: // normalize small integer return values if (fgGlobalMorph && varTypeIsSmall(info.compRetType) && (op1 != NULL) && (op1->TypeGet() != TYP_VOID) && fgCastNeeded(op1, info.compRetType)) { // Small-typed return values are normalized by the callee op1 = gtNewCastNode(TYP_INT, op1, info.compRetType); // Propagate GTF_COLON_COND op1->gtFlags|=(tree->gtFlags & GTF_COLON_COND); tree->gtOp.gtOp1 = fgMorphCast(op1); // Propagate side effect flags tree->gtFlags &= ~GTF_ALL_EFFECT; tree->gtFlags |= (tree->gtOp.gtOp1->gtFlags & GTF_ALL_EFFECT); return tree; } break; case GT_EQ: case GT_NE: // Check for typeof(...) == obj.GetType() // Also check for typeof(...) == typeof(...) // IMPORTANT NOTE: this optimization relies on a one-to-one mapping between // type handles and instances of System.Type // If this invariant is ever broken, the optimization will need updating #ifdef LEGACY_BACKEND if ( op1->gtOper == GT_CALL && op2->gtOper == GT_CALL && ((op1->gtCall.gtCallMoreFlags & GTF_CALL_M_SPECIAL_INTRINSIC) || (op1->gtCall.gtCallType == CT_HELPER)) && ((op2->gtCall.gtCallMoreFlags & GTF_CALL_M_SPECIAL_INTRINSIC) || (op2->gtCall.gtCallType == CT_HELPER))) #else if ((((op1->gtOper == GT_INTRINSIC) && (op1->gtIntrinsic.gtIntrinsicId == CORINFO_INTRINSIC_Object_GetType)) || ((op1->gtOper == GT_CALL) && (op1->gtCall.gtCallType == CT_HELPER))) && (((op2->gtOper == GT_INTRINSIC) && (op2->gtIntrinsic.gtIntrinsicId == CORINFO_INTRINSIC_Object_GetType)) || ((op2->gtOper == GT_CALL) && (op2->gtCall.gtCallType == CT_HELPER)))) #endif { GenTreePtr pGetClassFromHandle; GenTreePtr pGetType; #ifdef LEGACY_BACKEND bool bOp1ClassFromHandle = gtIsTypeHandleToRuntimeTypeHelper(op1); bool bOp2ClassFromHandle = gtIsTypeHandleToRuntimeTypeHelper(op2); #else bool bOp1ClassFromHandle = op1->gtOper == GT_CALL ? gtIsTypeHandleToRuntimeTypeHelper(op1) : false; bool bOp2ClassFromHandle = op2->gtOper == GT_CALL ? gtIsTypeHandleToRuntimeTypeHelper(op2) : false; #endif // Optimize typeof(...) == typeof(...) // Typically this occurs in generic code that attempts a type switch // e.g. typeof(T) == typeof(int) if (bOp1ClassFromHandle && bOp2ClassFromHandle) { GenTreePtr classFromHandleArg1 = tree->gtOp.gtOp1->gtCall.gtCallArgs->gtOp.gtOp1; GenTreePtr classFromHandleArg2 = tree->gtOp.gtOp2->gtCall.gtCallArgs->gtOp.gtOp1; GenTreePtr compare = gtNewOperNode(oper, TYP_INT, classFromHandleArg1, classFromHandleArg2); compare->gtFlags |= tree->gtFlags & (GTF_RELOP_JMP_USED | GTF_RELOP_QMARK | GTF_DONT_CSE); // Morph and return return fgMorphTree(compare); } else if (bOp1ClassFromHandle || bOp2ClassFromHandle) { // // Now check for GetClassFromHandle(handle) == obj.GetType() // if (bOp1ClassFromHandle) { pGetClassFromHandle = tree->gtOp.gtOp1; pGetType = op2; } else { pGetClassFromHandle = tree->gtOp.gtOp2; pGetType = op1; } GenTreePtr pGetClassFromHandleArgument = pGetClassFromHandle->gtCall.gtCallArgs->gtOp.gtOp1; GenTreePtr pConstLiteral = pGetClassFromHandleArgument; // Unwrap GT_NOP node used to prevent constant folding if (pConstLiteral->gtOper == GT_NOP && pConstLiteral->gtType == TYP_I_IMPL) { pConstLiteral = pConstLiteral->gtOp.gtOp1; } // In the ngen case, we have to go thru an indirection to get the right handle. if (pConstLiteral->gtOper == GT_IND) { pConstLiteral = pConstLiteral->gtOp.gtOp1; } #ifdef LEGACY_BACKEND if (pGetType->gtCall.gtCallMoreFlags & GTF_CALL_M_SPECIAL_INTRINSIC && info.compCompHnd->getIntrinsicID(pGetType->gtCall.gtCallMethHnd) == CORINFO_INTRINSIC_Object_GetType && #else if ((pGetType->gtOper == GT_INTRINSIC) && (pGetType->gtIntrinsic.gtIntrinsicId == CORINFO_INTRINSIC_Object_GetType) && #endif pConstLiteral->gtOper == GT_CNS_INT && pConstLiteral->gtType == TYP_I_IMPL) { CORINFO_CLASS_HANDLE clsHnd = CORINFO_CLASS_HANDLE(pConstLiteral->gtIntCon.gtCompileTimeHandle); if (info.compCompHnd->canInlineTypeCheckWithObjectVTable(clsHnd)) { // Method Table tree #ifdef LEGACY_BACKEND GenTreePtr objMT = gtNewOperNode(GT_IND, TYP_I_IMPL, pGetType->gtCall.gtCallObjp); #else GenTreePtr objMT = gtNewOperNode(GT_IND, TYP_I_IMPL, pGetType->gtUnOp.gtOp1); #endif objMT->gtFlags |= GTF_EXCEPT; // Null ref exception if object is null compCurBB->bbFlags |= BBF_HAS_VTABREF; optMethodFlags |= OMF_HAS_VTABLEREF; // Method table constant GenTreePtr cnsMT = pGetClassFromHandleArgument; GenTreePtr compare = gtNewOperNode(oper, TYP_INT, objMT, cnsMT); compare->gtFlags |= tree->gtFlags & (GTF_RELOP_JMP_USED | GTF_RELOP_QMARK | GTF_DONT_CSE); // Morph and return return fgMorphTree(compare); } } } } fgMorphRecognizeBoxNullable(tree); op1 = tree->gtOp.gtOp1; op2 = tree->gtGetOp2(); break; #ifdef _TARGET_ARM_ case GT_INTRINSIC: if (tree->gtIntrinsic.gtIntrinsicId == CORINFO_INTRINSIC_Round) { switch (tree->TypeGet()) { case TYP_DOUBLE: return fgMorphIntoHelperCall(tree, CORINFO_HELP_DBLROUND, gtNewArgList(op1)); case TYP_FLOAT: return fgMorphIntoHelperCall(tree, CORINFO_HELP_FLTROUND, gtNewArgList(op1)); default: unreached(); } } break; #endif default: break; } #if !CPU_HAS_FP_SUPPORT tree = fgMorphToEmulatedFP(tree); #endif /* Could this operator throw an exception? */ if (fgGlobalMorph && tree->OperMayThrow()) { if ((tree->OperGet() != GT_IND) || fgAddrCouldBeNull(tree->gtOp.gtOp1)) { /* Mark the tree node as potentially throwing an exception */ tree->gtFlags |= GTF_EXCEPT; } } /*------------------------------------------------------------------------- * Process the first operand, if any */ if (op1) { #if LOCAL_ASSERTION_PROP // If we are entering the "then" part of a Qmark-Colon we must // save the state of the current copy assignment table // so that we can restore this state when entering the "else" part if (isQmarkColon) { noway_assert(optLocalAssertionProp); if (optAssertionCount) { noway_assert(optAssertionCount <= optMaxAssertionCount); // else ALLOCA() is a bad idea unsigned tabSize = optAssertionCount * sizeof(AssertionDsc); origAssertionTab = (AssertionDsc*) ALLOCA(tabSize); origAssertionCount = optAssertionCount; memcpy(origAssertionTab, optAssertionTabPrivate, tabSize); } else { origAssertionCount = 0; origAssertionTab = NULL; } } #endif // LOCAL_ASSERTION_PROP // We might need a new MorphAddressContext context. (These are used to convey // parent context about how addresses being calculated will be used; see the // specification comment for MorphAddrContext for full details.) // Assume it's an Ind context to start. MorphAddrContext subIndMac1(MACK_Ind); MorphAddrContext* subMac1 = mac; if (subMac1 == NULL || subMac1->m_kind == MACK_Ind || subMac1->m_kind == MACK_CopyBlock) { switch (tree->gtOper) { case GT_ADDR: if (subMac1 == NULL) { subMac1 = &subIndMac1; subMac1->m_kind = MACK_Addr; } break; case GT_COMMA: // In a comma, the incoming context only applies to the rightmost arg of the // comma list. The left arg (op1) gets a fresh context. subMac1 = NULL; break; case GT_COPYBLK: case GT_COPYOBJ: assert(subMac1 == NULL); // Should only occur at top level, since value is void. subMac1 = &s_CopyBlockMAC; break; case GT_LIST: // If the list is the first arg of a copy block, its two args should be evaluated as // IND-context addresses, separately. if (subMac1 != NULL && subMac1->m_kind == MACK_CopyBlock) { subMac1 = &subIndMac1; } break; case GT_IND: case GT_INITBLK: case GT_OBJ: subMac1 = &subIndMac1; break; default: break; } } // For additions, if we're in an IND context keep track of whether // all offsets added to the address are constant, and their sum. if (tree->gtOper == GT_ADD && subMac1 != NULL) { assert(subMac1->m_kind == MACK_Ind || subMac1->m_kind == MACK_Addr); // Can't be a CopyBlock. GenTreePtr otherOp = tree->gtOp.gtOp2; // Is the other operator a constant? if (otherOp->IsCnsIntOrI()) { ClrSafeInt<size_t> totalOffset(subMac1->m_totalOffset); totalOffset += otherOp->gtIntConCommon.IconValue(); if (totalOffset.IsOverflow()) { // We will consider an offset so large as to overflow as "not a constant" -- // we will do a null check. subMac1->m_allConstantOffsets = false; } else { subMac1->m_totalOffset += otherOp->gtIntConCommon.IconValue(); } } else { subMac1->m_allConstantOffsets = false; } } tree->gtOp.gtOp1 = op1 = fgMorphTree(op1, subMac1); #if LOCAL_ASSERTION_PROP // If we are exiting the "then" part of a Qmark-Colon we must // save the state of the current copy assignment table // so that we can merge this state with the "else" part exit if (isQmarkColon) { noway_assert(optLocalAssertionProp); if (optAssertionCount) { noway_assert(optAssertionCount <= optMaxAssertionCount); // else ALLOCA() is a bad idea unsigned tabSize = optAssertionCount * sizeof(AssertionDsc); thenAssertionTab = (AssertionDsc*) ALLOCA(tabSize); thenAssertionCount = optAssertionCount; memcpy(thenAssertionTab, optAssertionTabPrivate, tabSize); } else { thenAssertionCount = 0; thenAssertionTab = NULL; } } #endif // LOCAL_ASSERTION_PROP /* Morphing along with folding and inlining may have changed the * side effect flags, so we have to reset them * * NOTE: Don't reset the exception flags on nodes that may throw */ noway_assert(tree->gtOper != GT_CALL); if ((tree->gtOper != GT_INTRINSIC) || !IsIntrinsicImplementedByUserCall(tree->gtIntrinsic.gtIntrinsicId)) { tree->gtFlags &= ~GTF_CALL; } if (!tree->OperMayThrow()) tree->gtFlags &= ~GTF_EXCEPT; /* Propagate the new flags */ tree->gtFlags |= (op1->gtFlags & GTF_ALL_EFFECT); // &aliasedVar doesn't need GTF_GLOB_REF, though alisasedVar does // Similarly for clsVar if (oper == GT_ADDR && (op1->gtOper == GT_LCL_VAR || op1->gtOper == GT_CLS_VAR)) tree->gtFlags &= ~GTF_GLOB_REF; } // if (op1) /*------------------------------------------------------------------------- * Process the second operand, if any */ if (op2) { #if LOCAL_ASSERTION_PROP // If we are entering the "else" part of a Qmark-Colon we must // reset the state of the current copy assignment table if (isQmarkColon) { noway_assert(optLocalAssertionProp); optAssertionReset(0); if (origAssertionCount) { size_t tabSize = origAssertionCount * sizeof(AssertionDsc); memcpy(optAssertionTabPrivate, origAssertionTab, tabSize); optAssertionReset(origAssertionCount); } } #endif // LOCAL_ASSERTION_PROP // We might need a new MorphAddressContext context to use in evaluating op2. // (These are used to convey parent context about how addresses being calculated // will be used; see the specification comment for MorphAddrContext for full details.) // Assume it's an Ind context to start. MorphAddrContext subIndMac2(MACK_Ind); switch (tree->gtOper) { case GT_ADD: if (mac != NULL && mac->m_kind == MACK_Ind) { GenTreePtr otherOp = tree->gtOp.gtOp1; // Is the other operator a constant? if (otherOp->IsCnsIntOrI()) { mac->m_totalOffset += otherOp->gtIntConCommon.IconValue(); } else { mac->m_allConstantOffsets = false; } } break; case GT_LIST: if (mac != NULL && mac->m_kind == MACK_CopyBlock) { mac = &subIndMac2; } break; default: break; } tree->gtOp.gtOp2 = op2 = fgMorphTree(op2, mac); /* Propagate the side effect flags from op2 */ tree->gtFlags |= (op2->gtFlags & GTF_ALL_EFFECT); #if LOCAL_ASSERTION_PROP // If we are exiting the "else" part of a Qmark-Colon we must // merge the state of the current copy assignment table with // that of the exit of the "then" part. if (isQmarkColon) { noway_assert(optLocalAssertionProp); // If either exit table has zero entries then // the merged table also has zero entries if (optAssertionCount == 0 || thenAssertionCount == 0) { optAssertionReset(0); } else { size_t tabSize = optAssertionCount * sizeof(AssertionDsc); if ( (optAssertionCount != thenAssertionCount) || (memcmp(thenAssertionTab, optAssertionTabPrivate, tabSize) != 0) ) { // Yes they are different so we have to find the merged set // Iterate over the copy asgn table removing any entries // that do not have an exact match in the thenAssertionTab AssertionIndex index = 1; while (index <= optAssertionCount) { AssertionDsc* curAssertion = optGetAssertion(index); for (unsigned j=0; j < thenAssertionCount; j++) { AssertionDsc* thenAssertion = &thenAssertionTab[j]; // Do the left sides match? if ((curAssertion->op1.lcl.lclNum == thenAssertion->op1.lcl.lclNum) && (curAssertion->assertionKind == thenAssertion->assertionKind)) { // Do the right sides match? if ((curAssertion->op2.kind == thenAssertion->op2.kind) && (curAssertion->op2.lconVal == thenAssertion->op2.lconVal)) { goto KEEP; } else { goto REMOVE; } } } // // If we fall out of the loop above then we didn't find // any matching entry in the thenAssertionTab so it must // have been killed on that path so we remove it here // REMOVE: // The data at optAssertionTabPrivate[i] is to be removed #ifdef DEBUG if (verbose) { printf("The QMARK-COLON "); printTreeID(tree); printf(" removes assertion candidate #%d\n", index); } #endif optAssertionRemove(index); continue; KEEP: // The data at optAssertionTabPrivate[i] is to be kept index++; } } } } #endif // LOCAL_ASSERTION_PROP } // if (op2) DONE_MORPHING_CHILDREN: /*------------------------------------------------------------------------- * Now do POST-ORDER processing */ #if FEATURE_FIXED_OUT_ARGS && !defined(_TARGET_64BIT_) // Variable shifts of a long end up being helper calls, so mark the tree as such. This // is potentially too conservative, since they'll get treated as having side effects. // It is important to mark them as calls so if they are part of an argument list, // they will get sorted and processed properly (for example, it is important to handle // all nested calls before putting struct arguments in the argument registers). We // could mark the trees just before argument processing, but it would require a full // tree walk of the argument tree, so we just do it here, instead, even though we'll // mark non-argument trees (that will still get converted to calls, anyway). if ((oper == GT_LSH || oper == GT_RSH || oper == GT_RSZ) && (tree->TypeGet() == TYP_LONG) && (op2->OperGet() != GT_CNS_INT)) { tree->gtFlags |= GTF_CALL; } #endif // FEATURE_FIXED_OUT_ARGS && !_TARGET_64BIT_ if (varTypeIsGC(tree->TypeGet()) && (op1 && !varTypeIsGC(op1->TypeGet())) && (op2 && !varTypeIsGC(op2->TypeGet()))) { // The tree is really not GC but was marked as such. Now that the // children have been unmarked, unmark the tree too. // Remember that GT_COMMA inherits it's type only from op2 if (tree->gtOper == GT_COMMA) tree->gtType = genActualType(op2->TypeGet()); else tree->gtType = genActualType(op1->TypeGet()); } GenTreePtr oldTree = tree; GenTreePtr qmarkOp1 = NULL; GenTreePtr qmarkOp2 = NULL; if ((tree->OperGet() == GT_QMARK) && (tree->gtOp.gtOp2->OperGet() == GT_COLON)) { qmarkOp1 = oldTree->gtOp.gtOp2->gtOp.gtOp1; qmarkOp2 = oldTree->gtOp.gtOp2->gtOp.gtOp2; } // Try to fold it, maybe we get lucky, tree = gtFoldExpr(tree); if (oldTree != tree) { /* if gtFoldExpr returned op1 or op2 then we are done */ if ((tree == op1) || (tree == op2) || (tree == qmarkOp1) || (tree == qmarkOp2)) return tree; /* If we created a comma-throw tree then we need to morph op1 */ if (fgIsCommaThrow(tree)) { tree->gtOp.gtOp1 = fgMorphTree(tree->gtOp.gtOp1); fgMorphTreeDone(tree); return tree; } return tree; } else if (tree->OperKind() & GTK_CONST) { return tree; } /* gtFoldExpr could have used setOper to change the oper */ oper = tree->OperGet(); typ = tree->TypeGet(); /* gtFoldExpr could have changed op1 and op2 */ op1 = tree->gtOp.gtOp1; op2 = tree->gtGetOp2(); // Do we have an integer compare operation? // if (tree->OperIsCompare() && varTypeIsIntegralOrI(tree->TypeGet())) { // Are we comparing against zero? // if (op2->IsZero()) { // Request that the codegen for op1 sets the condition flags // when it generates the code for op1. // // Codegen for op1 must set the condition flags if // this method returns true. // op1->gtRequestSetFlags(); } } /*------------------------------------------------------------------------- * Perform the required oper-specific postorder morphing */ GenTreePtr temp; GenTreePtr cns1, cns2; GenTreePtr thenNode; GenTreePtr elseNode; size_t ival1, ival2; GenTreePtr lclVarTree; GenTreeLclVarCommon* lclVarCmnTree; FieldSeqNode* fieldSeq = NULL; switch (oper) { case GT_ASG: lclVarTree = fgIsIndirOfAddrOfLocal(op1); if (lclVarTree != NULL) { lclVarTree->gtFlags |= GTF_VAR_DEF; } /* If we are storing a small type, we might be able to omit a cast */ if ((op1->gtOper == GT_IND) && varTypeIsSmall(op1->TypeGet())) { if (!gtIsActiveCSE_Candidate(op2) && (op2->gtOper == GT_CAST) && !op2->gtOverflow()) { var_types castType = op2->CastToType(); // If we are performing a narrowing cast and // castType is larger or the same as op1's type // then we can discard the cast. if (varTypeIsSmall(castType) && (castType >= op1->TypeGet())) { tree->gtOp.gtOp2 = op2 = op2->gtCast.CastOp(); } } else if (op2->OperIsCompare() && varTypeIsByte(op1->TypeGet())) { /* We don't need to zero extend the setcc instruction */ op2->gtType = TYP_BYTE; } } // If we introduced a CSE we may need to undo the optimization above // (i.e. " op2->gtType = TYP_BYTE;" which depends upon op1 being a GT_IND of a byte type) // When we introduce the CSE we remove the GT_IND and subsitute a GT_LCL_VAR in it place. else if (op2->OperIsCompare() && (op2->gtType == TYP_BYTE) && (op1->gtOper == GT_LCL_VAR)) { unsigned varNum = op1->gtLclVarCommon.gtLclNum; LclVarDsc * varDsc = &lvaTable[varNum]; /* We again need to zero extend the setcc instruction */ op2->gtType = varDsc->TypeGet(); } __fallthrough; case GT_COPYOBJ: case GT_COPYBLK: case GT_INITBLK: fgAssignSetVarDef(tree); __fallthrough; case GT_ASG_ADD: case GT_ASG_SUB: case GT_ASG_MUL: case GT_ASG_DIV: case GT_ASG_MOD: case GT_ASG_UDIV: case GT_ASG_UMOD: case GT_ASG_OR: case GT_ASG_XOR: case GT_ASG_AND: case GT_ASG_LSH: case GT_ASG_RSH: case GT_ASG_RSZ: /* We can't CSE the LHS of an assignment */ /* We also must set in the pre-morphing phase, otherwise assertionProp doesn't see it */ op1->gtFlags |= GTF_DONT_CSE; break; case GT_EQ: case GT_NE: /* Make sure we're allowed to do this */ if (optValnumCSE_phase) { // It is not safe to reorder/delete CSE's break; } cns2 = op2; /* Check for "(expr +/- icon1) ==/!= (non-zero-icon2)" */ if (cns2->gtOper == GT_CNS_INT && cns2->gtIntCon.gtIconVal != 0) { op1 = tree->gtOp.gtOp1; /* Since this can occur repeatedly we use a while loop */ while ((op1->gtOper == GT_ADD || op1->gtOper == GT_SUB) && (op1->gtOp.gtOp2->gtOper == GT_CNS_INT) && (op1->gtType == TYP_INT) && (op1->gtOverflow() == false)) { /* Got it; change "x+icon1==icon2" to "x==icon2-icon1" */ ival1 = op1->gtOp.gtOp2->gtIntCon.gtIconVal; ival2 = cns2->gtIntCon.gtIconVal; if (op1->gtOper == GT_ADD) { ival2 -= ival1; } else { ival2 += ival1; } cns2->gtIntCon.gtIconVal = ival2; #ifdef _TARGET_64BIT_ // we need to properly re-sign-extend or truncate as needed. cns2->AsIntCon()->TruncateOrSignExtend32(); #endif // _TARGET_64BIT_ op1 = tree->gtOp.gtOp1 = op1->gtOp.gtOp1; } } // // Here we look for the following tree // // EQ/NE // / \ // op1 CNS 0/1 // ival2 = INT_MAX; // The value of INT_MAX for ival2 just means that the constant value is not 0 or 1 // cast to unsigned allows test for both 0 and 1 if ((cns2->gtOper == GT_CNS_INT) && (((size_t) cns2->gtIntConCommon.IconValue()) <= 1U)) { ival2 = (size_t) cns2->gtIntConCommon.IconValue(); } else // cast to UINT64 allows test for both 0 and 1 if ((cns2->gtOper == GT_CNS_LNG) && (((UINT64) cns2->gtIntConCommon.LngValue()) <= 1ULL)) { ival2 = (size_t) cns2->gtIntConCommon.LngValue(); } if (ival2 != INT_MAX) { // If we don't have a comma and relop, we can't do this optimization // if ((op1->gtOper == GT_COMMA) && (op1->gtOp.gtOp2->OperIsCompare())) { // Here we look for the following transformation // // EQ/NE Possible REVERSE(RELOP) // / \ / \ // COMMA CNS 0/1 -> COMMA relop_op2 // / \ / \ // x RELOP x relop_op1 // / \ // relop_op1 relop_op2 // // // GenTreePtr comma = op1; GenTreePtr relop = comma->gtOp.gtOp2; GenTreePtr relop_op1 = relop->gtOp.gtOp1; bool reverse = ((ival2 == 0) == (oper == GT_EQ)); if (reverse) { gtReverseCond(relop); } relop->gtOp.gtOp1 = comma; comma->gtOp.gtOp2 = relop_op1; // Comma now has fewer nodes underneath it, so we need to regenerate its flags comma->gtFlags &= ~GTF_ALL_EFFECT; comma->gtFlags |= (comma->gtOp.gtOp1->gtFlags) & GTF_ALL_EFFECT; comma->gtFlags |= (comma->gtOp.gtOp2->gtFlags) & GTF_ALL_EFFECT; noway_assert((relop->gtFlags & GTF_RELOP_JMP_USED) == 0); noway_assert((relop->gtFlags & GTF_REVERSE_OPS) == 0); relop->gtFlags |= tree->gtFlags & (GTF_RELOP_JMP_USED|GTF_RELOP_QMARK|GTF_DONT_CSE|GTF_ALL_EFFECT); return relop; } if (op1->gtOper == GT_COMMA) { // Here we look for the following tree // and when the LCL_VAR is a temp we can fold the tree: // // EQ/NE EQ/NE // / \ / \ // COMMA CNS 0/1 -> RELOP CNS 0/1 // / \ / \ // ASG LCL_VAR // / \ // LCL_VAR RELOP // / \ // GenTreePtr asg = op1->gtOp.gtOp1; GenTreePtr lcl = op1->gtOp.gtOp2; /* Make sure that the left side of the comma is the assignment of the LCL_VAR */ if (asg->gtOper != GT_ASG) goto SKIP; /* The right side of the comma must be a LCL_VAR temp */ if (lcl->gtOper != GT_LCL_VAR) goto SKIP; unsigned lclNum = lcl->gtLclVarCommon.gtLclNum; noway_assert(lclNum < lvaCount); /* If the LCL_VAR is not a temp then bail, a temp has a single def */ if (!lvaTable[lclNum].lvIsTemp) goto SKIP; #if FEATURE_ANYCSE /* If the LCL_VAR is a CSE temp then bail, it could have multiple defs/uses */ // Fix 383856 X86/ARM ILGEN if (lclNumIsCSE(lclNum)) goto SKIP; #endif /* We also must be assigning the result of a RELOP */ if (asg->gtOp.gtOp1->gtOper != GT_LCL_VAR) goto SKIP; /* Both of the LCL_VAR must match */ if (asg->gtOp.gtOp1->gtLclVarCommon.gtLclNum != lclNum) goto SKIP; /* If right side of asg is not a RELOP then skip */ if (!asg->gtOp.gtOp2->OperIsCompare()) goto SKIP; LclVarDsc * varDsc = lvaTable + lclNum; /* Set op1 to the right side of asg, (i.e. the RELOP) */ op1 = asg->gtOp.gtOp2; DEBUG_DESTROY_NODE(asg->gtOp.gtOp1); DEBUG_DESTROY_NODE(lcl); /* This local variable should never be used again */ // <BUGNUM> // VSW 184221: Make RefCnt to zero to indicate that this local var // is not used any more. (Keey the lvType as is.) // Otherwise lvOnFrame will be set to true in Compiler::raMarkStkVars // And then emitter::emitEndCodeGen will assert in the following line: // noway_assert( dsc->lvTracked); // </BUGNUM> noway_assert(varDsc->lvRefCnt == 0 || // lvRefCnt may not have been set yet. varDsc->lvRefCnt == 2 // Or, we assume this tmp should only be used here, // and it only shows up twice. ); lvaTable[lclNum].lvRefCnt = 0; lvaTable[lclNum].lvaResetSortAgainFlag(this); } if (op1->OperIsCompare()) { // Here we look for the following tree // // EQ/NE -> RELOP/!RELOP // / \ / \ // RELOP CNS 0/1 // / \ // // Note that we will remove/destroy the EQ/NE node and move // the RELOP up into it's location. /* Here we reverse the RELOP if necessary */ bool reverse = ((ival2 == 0) == (oper == GT_EQ)); if (reverse) { gtReverseCond(op1); } /* Propagate gtType of tree into op1 in case it is TYP_BYTE for setcc optimization */ op1->gtType = tree->gtType; noway_assert((op1->gtFlags & GTF_RELOP_JMP_USED) == 0); op1->gtFlags |= tree->gtFlags & (GTF_RELOP_JMP_USED|GTF_RELOP_QMARK|GTF_DONT_CSE); DEBUG_DESTROY_NODE(tree); return op1; } // // Now we check for a compare with the result of an '&' operator // // Here we look for the following transformation: // // EQ/NE EQ/NE // / \ / \ // AND CNS 0/1 -> AND CNS 0 // / \ / \ // RSZ/RSH CNS 1 x CNS (1 << y) // / \ // x CNS_INT +y if (op1->gtOper == GT_AND) { GenTreePtr andOp = op1; GenTreePtr rshiftOp = andOp->gtOp.gtOp1; if ((rshiftOp->gtOper != GT_RSZ) && (rshiftOp->gtOper != GT_RSH)) goto SKIP; if (!rshiftOp->gtOp.gtOp2->IsCnsIntOrI()) goto SKIP; ssize_t shiftAmount = rshiftOp->gtOp.gtOp2->gtIntCon.gtIconVal; if (shiftAmount < 0) goto SKIP; if (andOp->gtType == TYP_INT) { if (!andOp->gtOp.gtOp2->IsCnsIntOrI()) goto SKIP; if (andOp->gtOp.gtOp2->gtIntCon.gtIconVal != 1) goto SKIP; if (shiftAmount > 31) goto SKIP; UINT32 newAndOperand = ((UINT32) 1) << shiftAmount; andOp->gtOp.gtOp2->gtIntCon.gtIconVal = newAndOperand; // Reverse the cond if necessary if (ival2 == 1) { gtReverseCond(tree); cns2->gtIntCon.gtIconVal = 0; oper = tree->gtOper; } } else if (andOp->gtType == TYP_LONG) { if (andOp->gtOp.gtOp2->gtOper != GT_CNS_NATIVELONG) goto SKIP; if (andOp->gtOp.gtOp2->gtIntConCommon.LngValue() != 1) goto SKIP; if (shiftAmount > 63) goto SKIP; UINT64 newAndOperand = ((UINT64) 1) << shiftAmount; andOp->gtOp.gtOp2->gtIntConCommon.SetLngValue(newAndOperand); // Reverse the cond if necessary if (ival2 == 1) { gtReverseCond(tree); cns2->gtIntConCommon.SetLngValue(0); oper = tree->gtOper; } } andOp->gtOp.gtOp1 = rshiftOp->gtOp.gtOp1; DEBUG_DESTROY_NODE(rshiftOp->gtOp.gtOp2); DEBUG_DESTROY_NODE(rshiftOp); } } // END if (ival2 != INT_MAX) SKIP: /* Now check for compares with small constant longs that can be cast to int */ if (!cns2->OperIsConst()) goto COMPARE; if (cns2->TypeGet() != TYP_LONG) goto COMPARE; /* Is the constant 31 bits or smaller? */ if ((cns2->gtIntConCommon.LngValue() >> 31) != 0) goto COMPARE; /* Is the first comparand mask operation of type long ? */ if (op1->gtOper != GT_AND) { /* Another interesting case: cast from int */ if (op1->gtOper == GT_CAST && op1->CastFromType() == TYP_INT && !gtIsActiveCSE_Candidate(op1) && // op1 cannot be a CSE candidate !op1->gtOverflow()) // cannot be an overflow checking cast { /* Simply make this into an integer comparison */ tree->gtOp.gtOp1 = op1->gtCast.CastOp(); tree->gtOp.gtOp2 = gtNewIconNode((int)cns2->gtIntConCommon.LngValue(), TYP_INT); } goto COMPARE; } noway_assert(op1->TypeGet() == TYP_LONG && op1->OperGet() == GT_AND); /* Is the result of the mask effectively an INT ? */ GenTreePtr andMask; andMask = op1->gtOp.gtOp2; if (andMask->gtOper != GT_CNS_NATIVELONG) goto COMPARE; if ((andMask->gtIntConCommon.LngValue() >> 32) != 0) goto COMPARE; /* Now we know that we can cast gtOp.gtOp1 of AND to int */ op1->gtOp.gtOp1 = gtNewCastNode(TYP_INT, op1->gtOp.gtOp1, TYP_INT); /* now replace the mask node (gtOp.gtOp2 of AND node) */ noway_assert(andMask == op1->gtOp.gtOp2); ival1 = (int) andMask->gtIntConCommon.LngValue(); andMask->SetOper(GT_CNS_INT); andMask->gtType = TYP_INT; andMask->gtIntCon.gtIconVal = ival1; /* now change the type of the AND node */ op1->gtType = TYP_INT; /* finally we replace the comparand */ ival2 = (int) cns2->gtIntConCommon.LngValue(); cns2->SetOper(GT_CNS_INT); cns2->gtType = TYP_INT; noway_assert(cns2 == op2); cns2->gtIntCon.gtIconVal = ival2; goto COMPARE; case GT_LT: case GT_LE: case GT_GE: case GT_GT: if ((tree->gtFlags & GTF_UNSIGNED) == 0) { if (op2->gtOper == GT_CNS_INT) { cns2 = op2; /* Check for "expr relop 1" */ if (cns2->gtIntCon.gtIconVal == +1) { /* Check for "expr >= 1" */ if (oper == GT_GE) { /* Change to "expr > 0" */ oper = GT_GT; goto SET_OPER; } /* Check for "expr < 1" */ else if (oper == GT_LT) { /* Change to "expr <= 0" */ oper = GT_LE; goto SET_OPER; } } /* Check for "expr relop -1" */ else if ((cns2->gtIntCon.gtIconVal == -1) && ((oper == GT_LE) || (oper == GT_GT))) { /* Check for "expr <= -1" */ if (oper == GT_LE) { /* Change to "expr < 0" */ oper = GT_LT; goto SET_OPER; } /* Check for "expr > -1" */ else if (oper == GT_GT) { /* Change to "expr >= 0" */ oper = GT_GE; SET_OPER: // IF we get here we should be changing 'oper' assert(tree->OperGet() != oper); // Keep the old ValueNumber for 'tree' as the new expr // will still compute the same value as before tree->SetOper(oper, GenTree::PRESERVE_VN); cns2->gtIntCon.gtIconVal = 0; // vnStore is null before the ValueNumber phase has run if (vnStore != nullptr) { // Update the ValueNumber for 'cns2', as we just changed it to 0 fgValueNumberTreeConst(cns2); } op2 = tree->gtOp.gtOp2 = gtFoldExpr(op2); } } } } COMPARE: noway_assert(tree->OperKind() & GTK_RELOP); /* Check if the result of the comparison is used for a jump. * If not then only the int (i.e. 32 bit) case is handled in * the code generator through the (x86) "set" instructions. * For the rest of the cases, the simplest way is to * "simulate" the comparison with ?: * * On ARM, we previously used the IT instruction, but the IT instructions * have mostly been declared obsolete and off-limits, so all cases on ARM * get converted to ?: */ if (!(tree->gtFlags & GTF_RELOP_JMP_USED) && fgMorphRelopToQmark(op1)) { /* We convert it to "(CMP_TRUE) ? (1):(0)" */ op1 = tree; op1->gtFlags |= (GTF_RELOP_JMP_USED | GTF_RELOP_QMARK | GTF_DONT_CSE); op1->gtRequestSetFlags(); op2 = new (this, GT_COLON) GenTreeColon(TYP_INT, gtNewIconNode(1), gtNewIconNode(0) ); op2 = fgMorphTree(op2); tree = gtNewQmarkNode(TYP_INT, op1, op2); fgMorphTreeDone(tree); return tree; } break; case GT_QMARK: /* If op1 is a comma throw node then we won't be keeping op2 */ if (fgIsCommaThrow(op1)) break; /* Get hold of the two branches */ noway_assert(op2->OperGet() == GT_COLON); elseNode = op2->AsColon()->ElseNode(); thenNode = op2->AsColon()->ThenNode(); /* Try to hoist assignments out of qmark colon constructs. ie. replace (cond?(x=a):(x=b)) with (x=(cond?a:b)). */ if (tree->TypeGet() == TYP_VOID && thenNode->OperGet() == GT_ASG && elseNode->OperGet() == GT_ASG && thenNode->TypeGet() != TYP_LONG && GenTree::Compare(thenNode->gtOp.gtOp1, elseNode->gtOp.gtOp1) && thenNode->gtOp.gtOp2->TypeGet() == elseNode->gtOp.gtOp2->TypeGet()) { noway_assert(thenNode->TypeGet() == elseNode->TypeGet()); GenTreePtr asg = thenNode; GenTreePtr colon = op2; colon->gtOp.gtOp1 = thenNode->gtOp.gtOp2; colon->gtOp.gtOp2 = elseNode->gtOp.gtOp2; tree->gtType = colon->gtType = asg->gtOp.gtOp2->gtType; asg->gtOp.gtOp2 = tree; // Asg will have all the flags that the QMARK had asg->gtFlags |= (tree->gtFlags & GTF_ALL_EFFECT); // Colon flag won't have the flags that x had. colon->gtFlags &= ~GTF_ALL_EFFECT; colon->gtFlags |= (colon->gtOp.gtOp1->gtFlags | colon->gtOp.gtOp2->gtFlags) & GTF_ALL_EFFECT; DEBUG_DESTROY_NODE(elseNode->gtOp.gtOp1); DEBUG_DESTROY_NODE(elseNode); return asg; } /* If the 'else' branch is empty swap the two branches and reverse the condition */ if (elseNode->IsNothingNode()) { /* This can only happen for VOID ?: */ noway_assert(op2->gtType == TYP_VOID); /* If the thenNode and elseNode are both nop nodes then optimize away the QMARK */ if (thenNode->IsNothingNode()) { // We may be able to throw away op1 (unless it has side-effects) if ((op1->gtFlags & GTF_SIDE_EFFECT) == 0) { /* Just return a a Nop Node */ return thenNode; } else { /* Just return the relop, but clear the special flags. Note that we can't do that for longs and floats (see code under COMPARE label above) */ if (!fgMorphRelopToQmark(op1->gtOp.gtOp1)) { op1->gtFlags &= ~(GTF_RELOP_QMARK | GTF_RELOP_JMP_USED); return op1; } } } else { GenTreePtr tmp = elseNode; op2->AsColon()->ElseNode() = elseNode = thenNode; op2->AsColon()->ThenNode() = thenNode = tmp; gtReverseCond(op1); } } #if !defined(_TARGET_ARM_) // If we have (cond)?0:1, then we just return "cond" for TYP_INTs // // Don't do this optimization for ARM: we always require assignment // to boolean to remain ?:, since we don't have any way to generate // this with straight-line code, like x86 does using setcc (at least // after the IT instruction is deprecated). if (genActualType(op1->gtOp.gtOp1->gtType) == TYP_INT && genActualType(typ) == TYP_INT && thenNode->gtOper == GT_CNS_INT && elseNode->gtOper == GT_CNS_INT) { ival1 = thenNode->gtIntCon.gtIconVal; ival2 = elseNode->gtIntCon.gtIconVal; // Is one constant 0 and the other 1? if ((ival1 | ival2) == 1 && (ival1 & ival2) == 0) { // If the constants are {1, 0}, reverse the condition if (ival1 == 1) gtReverseCond(op1); // Unmark GTF_RELOP_JMP_USED on the condition node so it knows that it // needs to materialize the result as a 0 or 1. noway_assert(op1->gtFlags & (GTF_RELOP_QMARK | GTF_RELOP_JMP_USED)); op1->gtFlags &= ~(GTF_RELOP_QMARK | GTF_RELOP_JMP_USED); DEBUG_DESTROY_NODE(tree); DEBUG_DESTROY_NODE(op2); return op1; } } #endif // !_TARGET_ARM_ break; // end case GT_QMARK case GT_MUL: #ifndef _TARGET_64BIT_ #if!LONG_MATH_REGPARAM if (typ == TYP_LONG) { // This must be GTF_MUL_64RSLT assert(tree->gtIsValid64RsltMul()); return tree; } #endif #endif // _TARGET_64BIT_ goto CM_OVF_OP; case GT_SUB: if (tree->gtOverflow()) goto CM_OVF_OP; /* Check for "op1 - cns2" , we change it to "op1 + (-cns2)" */ noway_assert(op2); if (op2->IsCnsIntOrI()) { /* Negate the constant and change the node to be "+" */ op2->gtIntConCommon.SetIconValue(-op2->gtIntConCommon.IconValue()); oper = GT_ADD; tree->ChangeOper(oper); goto CM_ADD_OP; } /* Check for "cns1 - op2" , we change it to "(cns1 + (-op2))" */ noway_assert(op1); if (op1->IsCnsIntOrI()) { noway_assert(varTypeIsIntOrI(tree)); tree->gtOp.gtOp2 = op2 = gtNewOperNode(GT_NEG, tree->gtType, op2); // The type of the new GT_NEG node should be the same // as the type of the tree, i.e. tree->gtType. fgMorphTreeDone(op2); oper = GT_ADD; tree->ChangeOper(oper); goto CM_ADD_OP; } /* No match - exit */ break; #ifdef _TARGET_ARM64_ case GT_DIV: if (!varTypeIsFloating(tree->gtType)) { // Codegen for this instruction needs to be able to throw two exceptions: fgAddCodeRef(compCurBB, bbThrowIndex(compCurBB), SCK_OVERFLOW, fgPtrArgCntCur); fgAddCodeRef(compCurBB, bbThrowIndex(compCurBB), SCK_DIV_BY_ZERO, fgPtrArgCntCur); } break; case GT_UDIV: // Codegen for this instruction needs to be able to throw one exception: fgAddCodeRef(compCurBB, bbThrowIndex(compCurBB), SCK_DIV_BY_ZERO, fgPtrArgCntCur); break; #endif case GT_ADD: CM_OVF_OP : if (tree->gtOverflow()) { tree->gtRequestSetFlags(); // Add the excptn-throwing basic block to jump to on overflow fgAddCodeRef(compCurBB, bbThrowIndex(compCurBB), SCK_OVERFLOW, fgPtrArgCntCur); // We can't do any commutative morphing for overflow instructions break; } CM_ADD_OP: case GT_OR: case GT_XOR: case GT_AND: /* Commute any non-REF constants to the right */ noway_assert(op1); if (op1->OperIsConst() && (op1->gtType != TYP_REF)) { // TODO-Review: We used to assert here that // noway_assert(!op2->OperIsConst() || !opts.OptEnabled(CLFLG_CONSTANTFOLD)); // With modifications to AddrTaken==>AddrExposed, we did more assertion propagation, // and would sometimes hit this assertion. This may indicate a missed "remorph". // Task is to re-enable this assertion and investigate. /* Swap the operands */ tree->gtOp.gtOp1 = op2; tree->gtOp.gtOp2 = op1; op1 = op2; op2 = tree->gtOp.gtOp2; } /* See if we can fold GT_ADD nodes. */ if (oper == GT_ADD) { /* Fold "((x+icon1)+(y+icon2)) to ((x+y)+(icon1+icon2))" */ if (op1->gtOper == GT_ADD && op2->gtOper == GT_ADD && !gtIsActiveCSE_Candidate(op2) && op1->gtOp.gtOp2->gtOper == GT_CNS_INT && op2->gtOp.gtOp2->gtOper == GT_CNS_INT && !op1->gtOverflow() && !op2->gtOverflow() ) { cns1 = op1->gtOp.gtOp2; cns2 = op2->gtOp.gtOp2; cns1->gtIntCon.gtIconVal += cns2->gtIntCon.gtIconVal; #ifdef _TARGET_64BIT_ if (cns1->TypeGet() == TYP_INT) { // we need to properly re-sign-extend or truncate after adding two int constants above cns1->AsIntCon()->TruncateOrSignExtend32(); } #endif //_TARGET_64BIT_ tree->gtOp.gtOp2 = cns1; DEBUG_DESTROY_NODE(cns2); op1->gtOp.gtOp2 = op2->gtOp.gtOp1; op1->gtFlags |= (op1->gtOp.gtOp2->gtFlags & GTF_ALL_EFFECT); DEBUG_DESTROY_NODE(op2); op2 = tree->gtOp.gtOp2; } if (op2->IsCnsIntOrI() && varTypeIsIntegralOrI(typ)) { /* Fold "((x+icon1)+icon2) to (x+(icon1+icon2))" */ if (op1->gtOper == GT_ADD && !gtIsActiveCSE_Candidate(op1) && op1->gtOp.gtOp2->IsCnsIntOrI() && !op1->gtOverflow() && op1->gtOp.gtOp2->OperGet() == op2->OperGet()) { cns1 = op1->gtOp.gtOp2; op2->gtIntConCommon.SetIconValue(cns1->gtIntConCommon.IconValue() + op2->gtIntConCommon.IconValue()); #ifdef _TARGET_64BIT_ if (op2->TypeGet() == TYP_INT) { // we need to properly re-sign-extend or truncate after adding two int constants above op2->AsIntCon()->TruncateOrSignExtend32(); } #endif //_TARGET_64BIT_ if (cns1->OperGet() == GT_CNS_INT) { op2->gtIntCon.gtFieldSeq = GetFieldSeqStore()->Append(cns1->gtIntCon.gtFieldSeq, op2->gtIntCon.gtFieldSeq); } DEBUG_DESTROY_NODE(cns1); tree->gtOp.gtOp1 = op1->gtOp.gtOp1; DEBUG_DESTROY_NODE(op1); op1 = tree->gtOp.gtOp1; } // Fold (x + 0). if ((op2->gtIntConCommon.IconValue() == 0) && !gtIsActiveCSE_Candidate(tree)) { // If this addition is adding an offset to a null pointer, // avoid the work and yield the null pointer immediately. // Dereferencing the pointer in either case will have the // same effect. if (!gtIsActiveCSE_Candidate(op1) && varTypeIsGC(op2->TypeGet())) { op2->gtType = tree->gtType; DEBUG_DESTROY_NODE(op1); DEBUG_DESTROY_NODE(tree); return op2; } // Remove the addition iff it won't change the tree type // to TYP_REF. if (!gtIsActiveCSE_Candidate(op2) && ((op1->TypeGet() == tree->TypeGet()) || (op1->TypeGet() != TYP_REF))) { if (fgGlobalMorph && (op2->OperGet() == GT_CNS_INT) && (op2->gtIntCon.gtFieldSeq != NULL) && (op2->gtIntCon.gtFieldSeq != FieldSeqStore::NotAField())) { fgAddFieldSeqForZeroOffset(op1, op2->gtIntCon.gtFieldSeq); } DEBUG_DESTROY_NODE(op2); DEBUG_DESTROY_NODE(tree); return op1; } } } } /* See if we can fold GT_MUL by const nodes */ else if (oper == GT_MUL && op2->IsCnsIntOrI() && !optValnumCSE_phase) { #ifndef _TARGET_64BIT_ noway_assert(typ <= TYP_UINT); #endif // _TARGET_64BIT_ noway_assert(!tree->gtOverflow()); ssize_t mult = op2->gtIntConCommon.IconValue(); bool op2IsConstIndex = op2->OperGet() == GT_CNS_INT && op2->gtIntCon.gtFieldSeq != nullptr && op2->gtIntCon.gtFieldSeq->IsConstantIndexFieldSeq(); assert(!op2IsConstIndex || op2->AsIntCon()->gtFieldSeq->m_next == nullptr); if (mult == 0) { // We may be able to throw away op1 (unless it has side-effects) if ((op1->gtFlags & GTF_SIDE_EFFECT) == 0) { DEBUG_DESTROY_NODE(op1); DEBUG_DESTROY_NODE(tree); return op2; // Just return the "0" node } // We need to keep op1 for the side-effects. Hang it off // a GT_COMMA node tree->ChangeOper(GT_COMMA); return tree; } size_t abs_mult = (mult >= 0) ? mult : -mult; size_t lowestBit = genFindLowestBit(abs_mult); bool changeToShift = false; // is it a power of two? (positive or negative) if (abs_mult == lowestBit) { // if negative negate (min-int does not need negation) if (mult < 0 && mult != SSIZE_T_MIN) { tree->gtOp.gtOp1 = op1 = gtNewOperNode(GT_NEG, op1->gtType, op1); fgMorphTreeDone(op1); } // If "op2" is a constant array index, the other multiplicand must be a constant. // Transfer the annotation to the other one. if (op2->OperGet() == GT_CNS_INT && op2->gtIntCon.gtFieldSeq != nullptr && op2->gtIntCon.gtFieldSeq->IsConstantIndexFieldSeq()) { assert(op2->gtIntCon.gtFieldSeq->m_next == nullptr); GenTreePtr otherOp = op1; if (otherOp->OperGet() == GT_NEG) otherOp = otherOp->gtOp.gtOp1; assert(otherOp->OperGet() == GT_CNS_INT); assert(otherOp->gtIntCon.gtFieldSeq == FieldSeqStore::NotAField()); otherOp->gtIntCon.gtFieldSeq = op2->gtIntCon.gtFieldSeq; } if (abs_mult == 1) { DEBUG_DESTROY_NODE(op2); DEBUG_DESTROY_NODE(tree); return op1; } /* Change the multiplication into a shift by log2(val) bits */ op2->gtIntConCommon.SetIconValue(genLog2(abs_mult)); changeToShift = true; } #if LEA_AVAILABLE else if ((lowestBit > 1) && jitIsScaleIndexMul(lowestBit) && optAvoidIntMult()) { int shift = genLog2(lowestBit); ssize_t factor = abs_mult >> shift; if (factor == 3 || factor == 5 || factor == 9) { // if negative negate (min-int does not need negation) if (mult < 0 && mult != SSIZE_T_MIN) { tree->gtOp.gtOp1 = op1 = gtNewOperNode(GT_NEG, op1->gtType, op1); fgMorphTreeDone(op1); } GenTreePtr factorIcon = gtNewIconNode(factor, TYP_I_IMPL); if (op2IsConstIndex) { factorIcon->AsIntCon()->gtFieldSeq = GetFieldSeqStore()->CreateSingleton(FieldSeqStore::ConstantIndexPseudoField); } // change the multiplication into a smaller multiplication (by 3, 5 or 9) and a shift tree->gtOp.gtOp1 = op1 = gtNewOperNode(GT_MUL, tree->gtType, op1, factorIcon); fgMorphTreeDone(op1); op2->gtIntConCommon.SetIconValue(shift); changeToShift = true; } } #endif // LEA_AVAILABLE if (changeToShift) { // vnStore is null before the ValueNumber phase has run if (vnStore != nullptr) { // Update the ValueNumber for 'op2', as we just changed the constant fgValueNumberTreeConst(op2); } oper = GT_LSH; // Keep the old ValueNumber for 'tree' as the new expr // will still compute the same value as before tree->ChangeOper(oper, GenTree::PRESERVE_VN); goto DONE_MORPHING_CHILDREN; } } else if (fgOperIsBitwiseRotationRoot(oper)) { tree = fgRecognizeAndMorphBitwiseRotation(tree); // fgRecognizeAndMorphBitwiseRotation may return a new tree oper = tree->OperGet(); typ = tree->TypeGet(); op1 = tree->gtOp.gtOp1; op2 = tree->gtOp.gtOp2; } break; case GT_CHS: case GT_NOT: case GT_NEG: /* Any constant cases should have been folded earlier */ noway_assert(!op1->OperIsConst() || !opts.OptEnabled(CLFLG_CONSTANTFOLD) || optValnumCSE_phase); break; case GT_CKFINITE: noway_assert(varTypeIsFloating(op1->TypeGet())); fgAddCodeRef(compCurBB, bbThrowIndex(compCurBB), SCK_ARITH_EXCPN, fgPtrArgCntCur); break; case GT_IND: // Can not remove a GT_IND if it is currently a CSE candidate. if (gtIsActiveCSE_Candidate(tree)) break; bool foldAndReturnTemp; foldAndReturnTemp = false; temp = nullptr; ival1 = 0; /* Try to Fold *(&X) into X */ if (op1->gtOper == GT_ADDR) { // Can not remove a GT_ADDR if it is currently a CSE candidate. if (gtIsActiveCSE_Candidate(op1)) break; temp = op1->gtOp.gtOp1; // X // In the test below, if they're both TYP_STRUCT, this of course does *not* mean that // they are the *same* struct type. In fact, they almost certainly aren't. If the // address has an associated field sequence, that identifies this case; go through // the "lcl_fld" path rather than this one. FieldSeqNode* addrFieldSeq = NULL; // This is an unused out parameter below. if ( typ == temp->TypeGet() && !GetZeroOffsetFieldMap()->Lookup(op1, &addrFieldSeq)) { foldAndReturnTemp = true; } else if (temp->OperIsLocal()) { unsigned lclNum = temp->gtLclVarCommon.gtLclNum; LclVarDsc * varDsc = &lvaTable[lclNum]; // We will try to optimize when we have a promoted struct promoted with a zero lvFldOffset if (varDsc->lvPromoted && (varDsc->lvFldOffset == 0)) { noway_assert(varTypeIsStruct(varDsc)); // We will try to optimize when we have a single field struct that is being struct promoted if (varDsc->lvFieldCnt == 1) { unsigned lclNumFld = varDsc->lvFieldLclStart; // just grab the promoted field LclVarDsc * fieldVarDsc = &lvaTable[lclNumFld]; // Also make sure that the tree type matches the fieldVarType and that it's lvFldOffset is zero if (fieldVarDsc->TypeGet() == tree->TypeGet() && (fieldVarDsc->lvFldOffset == 0)) { // We can just use the existing promoted field LclNum temp->gtLclVarCommon.SetLclNum(lclNumFld); temp->gtType = fieldVarDsc->TypeGet(); foldAndReturnTemp = true; } } } // If the type of the IND (typ) is a "small int", and the type of the local has the // same width, then we can reduce to just the local variable -- it will be // correctly normalized, and signed/unsigned differences won't matter. // // The below transformation cannot be applied if the local var needs to be normalized on load. else if ( varTypeIsSmall(typ) && (genTypeSize(lvaTable[lclNum].lvType) == genTypeSize(typ)) && !lvaTable[lclNum].lvNormalizeOnLoad() ) { tree->gtType = temp->gtType; foldAndReturnTemp = true; } else { // Assumes that when Lookup returns "false" it will leave "fieldSeq" unmodified (i.e. nullptr) assert(fieldSeq == nullptr); bool b = GetZeroOffsetFieldMap()->Lookup(op1, &fieldSeq); assert(b || fieldSeq == nullptr); if ((fieldSeq != nullptr) && (temp->OperGet() == GT_LCL_FLD)) { // Append the field sequence, change the type. temp->AsLclFld()->gtFieldSeq = GetFieldSeqStore()->Append(temp->AsLclFld()->gtFieldSeq, fieldSeq); temp->gtType = tree->TypeGet(); foldAndReturnTemp = true; } } // Otherwise will will fold this into a GT_LCL_FLD below // where we check (temp != nullptr) } else // !temp->OperIsLocal() { // We don't try to fold away the GT_IND/GT_ADDR for this case temp = nullptr; } } else if (op1->OperGet() == GT_ADD) { /* Try to change *(&lcl + cns) into lcl[cns] to prevent materialization of &lcl */ if (op1->gtOp.gtOp1->OperGet() == GT_ADDR && op1->gtOp.gtOp2->OperGet() == GT_CNS_INT && (!(opts.MinOpts() || opts.compDbgCode))) { // No overflow arithmetic with pointers noway_assert(!op1->gtOverflow()); temp = op1->gtOp.gtOp1->gtOp.gtOp1; if (!temp->OperIsLocal()) { temp = nullptr; break; } // Can not remove the GT_ADDR if it is currently a CSE candidate. if (gtIsActiveCSE_Candidate(op1->gtOp.gtOp1)) break; ival1 = op1->gtOp.gtOp2->gtIntCon.gtIconVal; fieldSeq = op1->gtOp.gtOp2->gtIntCon.gtFieldSeq; // Does the address have an associated zero-offset field sequence? FieldSeqNode* addrFieldSeq = NULL; if (GetZeroOffsetFieldMap()->Lookup(op1->gtOp.gtOp1, &addrFieldSeq)) { fieldSeq = GetFieldSeqStore()->Append(addrFieldSeq, fieldSeq); } if (ival1 == 0 && typ == temp->TypeGet() && temp->TypeGet() != TYP_STRUCT) { noway_assert(!varTypeIsGC(temp->TypeGet())); foldAndReturnTemp = true; } else { // The emitter can't handle large offsets if (ival1 != (unsigned short)ival1) break; // The emitter can get confused by invalid offsets if (ival1 >= Compiler::lvaLclSize(temp->gtLclVarCommon.gtLclNum)) break; #ifdef _TARGET_ARM_ // Check for a LclVar TYP_STRUCT with misalignment on a Floating Point field // if (varTypeIsFloating(tree->TypeGet())) { if ((ival1 % emitTypeSize(tree->TypeGet())) != 0) { tree->gtFlags |= GTF_IND_UNALIGNED; break; } } #endif } // Now we can fold this into a GT_LCL_FLD below // where we check (temp != nullptr) } } #ifdef DEBUG // If we have decided to fold, then temp cannot be nullptr if (foldAndReturnTemp) { assert(temp != nullptr); } #endif if (temp != nullptr) { noway_assert(op1->gtOper == GT_ADD || op1->gtOper == GT_ADDR); // If we haven't already decided to fold this expression // if (!foldAndReturnTemp) { noway_assert(temp->OperIsLocal()); LclVarDsc* varDsc = &(lvaTable[temp->AsLclVarCommon()->gtLclNum]); // Make sure we don't separately promote the fields of this struct. if (varDsc->lvRegStruct) { // We can enregister, but can't promote. varDsc->lvPromoted = false; } else { lvaSetVarDoNotEnregister(temp->gtLclVarCommon.gtLclNum DEBUG_ARG(DNER_LocalField)); } // We will turn a GT_LCL_VAR into a GT_LCL_FLD with an gtLclOffs of 'ival' // ot if we already have a GT_LCL_FLD we will adjust the gtLclOffs by adding 'ival' // Then we change the type of the GT_LCL_FLD to match the orginal GT_IND type. // if (temp->OperGet() == GT_LCL_FLD) { temp->AsLclFld()->gtLclOffs += (unsigned short)ival1; temp->AsLclFld()->gtFieldSeq = GetFieldSeqStore()->Append(temp->AsLclFld()->gtFieldSeq, fieldSeq); } else { temp->ChangeOper(GT_LCL_FLD); // Note that this makes the gtFieldSeq "NotAField"... temp->AsLclFld()->gtLclOffs = (unsigned short)ival1; if (fieldSeq != NULL) // If it does represent a field, note that. temp->AsLclFld()->gtFieldSeq = fieldSeq; } temp->gtType = tree->gtType; foldAndReturnTemp = true; } assert(foldAndReturnTemp == true); // Keep the DONT_CSE flag in sync // (i.e keep the original value of this flag from tree) // as it can be set for 'temp' because a GT_ADDR always marks it for it's op1 // temp->gtFlags &= ~GTF_DONT_CSE; temp->gtFlags |= (tree->gtFlags & GTF_DONT_CSE); noway_assert(op1->gtOper == GT_ADD || op1->gtOper == GT_ADDR); noway_assert(temp->gtType == tree->gtType); if (op1->OperGet() == GT_ADD) { DEBUG_DESTROY_NODE(op1->gtOp.gtOp1); // GT_ADDR DEBUG_DESTROY_NODE(op1->gtOp.gtOp2); // GT_CNS_INT } DEBUG_DESTROY_NODE(op1); // GT_ADD or GT_ADDR DEBUG_DESTROY_NODE(tree); // GT_IND return temp; } // Only do this optimization when we are in the global optimizer. Doing this after value numbering // could result in an invalid value number for the newly generated GT_IND node. if ((op1->OperGet() == GT_COMMA) && fgGlobalMorph) { // Perform the transform IND(COMMA(x, ..., z)) == COMMA(x, ..., IND(z)). // TBD: this transformation is currently necessary for correctness -- it might // be good to analyze the failures that result if we don't do this, and fix them // in other ways. Ideally, this should be optional. GenTreePtr commaNode = op1; unsigned treeFlags = tree->gtFlags; commaNode->gtType = typ; commaNode->gtFlags = (treeFlags & ~GTF_REVERSE_OPS); // Bashing the GT_COMMA flags here is dangerous, clear the GTF_REVERSE_OPS at least. #ifdef DEBUG commaNode->gtFlags |= GTF_MORPHED; #endif while (commaNode->gtOp.gtOp2->gtOper == GT_COMMA) { commaNode = commaNode->gtOp.gtOp2; commaNode->gtType = typ; commaNode->gtFlags = (treeFlags & ~GTF_REVERSE_OPS); // Bashing the GT_COMMA flags here is dangerous, clear the GTF_REVERSE_OPS at least. #ifdef DEBUG commaNode->gtFlags |= GTF_MORPHED; #endif } bool wasArrIndex = (tree->gtFlags & GTF_IND_ARR_INDEX) != 0; ArrayInfo arrInfo; if (wasArrIndex) { bool b = GetArrayInfoMap()->Lookup(tree, &arrInfo); assert(b); GetArrayInfoMap()->Remove(tree); } tree = op1; op1 = gtNewOperNode(GT_IND, typ, commaNode->gtOp.gtOp2); op1->gtFlags = treeFlags; if (wasArrIndex) { GetArrayInfoMap()->Set(op1, arrInfo); } #ifdef DEBUG op1->gtFlags |= GTF_MORPHED; #endif commaNode->gtOp.gtOp2 = op1; return tree; } break; case GT_ADDR: // Can not remove op1 if it is currently a CSE candidate. if (gtIsActiveCSE_Candidate(op1)) break; if (op1->OperGet() == GT_IND) { if ((op1->gtFlags & GTF_IND_ARR_INDEX) == 0) { // Can not remove a GT_ADDR if it is currently a CSE candidate. if (gtIsActiveCSE_Candidate(tree)) break; // Perform the transform ADDR(IND(...)) == (...). GenTreePtr addr = op1->gtOp.gtOp1; noway_assert(varTypeIsGC(addr->gtType) || addr->gtType == TYP_I_IMPL); DEBUG_DESTROY_NODE(op1); DEBUG_DESTROY_NODE(tree); return addr; } } else if (op1->gtOper == GT_CAST) { GenTreePtr casting = op1->gtCast.CastOp(); if (casting->gtOper == GT_LCL_VAR || casting->gtOper == GT_CLS_VAR) { DEBUG_DESTROY_NODE(op1); tree->gtOp.gtOp1 = op1 = casting; } } else if ((op1->gtOper == GT_COMMA) && !optValnumCSE_phase) { // Perform the transform ADDR(COMMA(x, ..., z)) == COMMA(x, ..., ADDR(z)). // (Be sure to mark "z" as an l-value...) GenTreePtr commaNode = op1; while (commaNode->gtOp.gtOp2->gtOper == GT_COMMA) { commaNode = commaNode->gtOp.gtOp2; } // The top-level addr might be annotated with a zeroOffset field. FieldSeqNode* zeroFieldSeq = nullptr; bool isZeroOffset = GetZeroOffsetFieldMap()->Lookup(tree, &zeroFieldSeq); tree = op1; commaNode->gtOp.gtOp2->gtFlags |= GTF_DONT_CSE; // If the node we're about to put under a GT_ADDR is a GT_IND, the indirection // doesn't need to be materialized, since we only want the addressing mode. Because // of this, this GT_IND is not a faulting indirection and we don't have to extract it // as a side effect. GenTree* commaOp2 = commaNode->gtOp.gtOp2; if (commaOp2->gtOper == GT_IND) { commaOp2->gtFlags |= GTF_IND_NONFAULTING; } op1 = gtNewOperNode(GT_ADDR, TYP_BYREF, commaOp2); if (isZeroOffset) { // Transfer the annotation to the new GT_ADDR node. GetZeroOffsetFieldMap()->Set(op1, zeroFieldSeq); } commaNode->gtOp.gtOp2 = op1; // Originally, I gave all the comma nodes type "byref". But the ADDR(IND(x)) == x transform // might give op1 a type different from byref (like, say, native int). So now go back and give // all the comma nodes the type of op1. commaNode = tree; while (commaNode->gtOper == GT_COMMA) { commaNode->gtType = op1->gtType; commaNode->gtFlags |= op1->gtFlags; #ifdef DEBUG commaNode->gtFlags |= GTF_MORPHED; #endif commaNode = commaNode->gtOp.gtOp2; } return tree; } /* op1 of a GT_ADDR is an l-value. Only r-values can be CSEed */ op1->gtFlags |= GTF_DONT_CSE; break; case GT_COLON: if (fgGlobalMorph) { /* Mark the nodes that are conditionally executed */ fgWalkTreePre(&tree, gtMarkColonCond); } /* Since we're doing this postorder we clear this if it got set by a child */ fgRemoveRestOfBlock = false; break; case GT_COMMA: /* Special case: trees that don't produce a value */ if ((op2->OperKind() & GTK_ASGOP) || (op2->OperGet() == GT_COMMA && op2->TypeGet() == TYP_VOID) || fgIsThrow(op2)) { typ = tree->gtType = TYP_VOID; } // If we are in the Valuenum CSE phase then don't morph away anything as these // nodes may have CSE defs/uses in them. // if (!optValnumCSE_phase) { //Extract the side effects from the left side of the comma. Since they don't "go" anywhere, this is //all we need. GenTreePtr op1SideEffects = NULL; // The addition of "GTF_MAKE_CSE" below prevents us from throwing away (for example) // hoisted expressions in loops. gtExtractSideEffList(op1, &op1SideEffects, (GTF_SIDE_EFFECT | GTF_MAKE_CSE)); if (op1SideEffects) { //Replace the left hand side with the side effect list. tree->gtOp.gtOp1 = op1SideEffects; tree->gtFlags |= (op1SideEffects->gtFlags & GTF_ALL_EFFECT); } else { /* The left operand is worthless, throw it away */ if (lvaLocalVarRefCounted) { lvaRecursiveDecRefCounts(op1); } op2->gtFlags |= (tree->gtFlags & (GTF_DONT_CSE | GTF_LATE_ARG)); DEBUG_DESTROY_NODE(tree); DEBUG_DESTROY_NODE(op1); return op2; } /* If the right operand is just a void nop node, throw it away */ if (op2->IsNothingNode() && op1->gtType == TYP_VOID) { op1->gtFlags |= (tree->gtFlags & (GTF_DONT_CSE | GTF_LATE_ARG)); DEBUG_DESTROY_NODE(tree); DEBUG_DESTROY_NODE(op2); return op1; } } break; case GT_JTRUE: /* Special case if fgRemoveRestOfBlock is set to true */ if (fgRemoveRestOfBlock) { if (fgIsCommaThrow(op1, true)) { GenTreePtr throwNode = op1->gtOp.gtOp1; noway_assert(throwNode->gtType == TYP_VOID); return throwNode; } noway_assert(op1->OperKind() & GTK_RELOP); noway_assert(op1->gtFlags & GTF_EXCEPT); // We need to keep op1 for the side-effects. Hang it off // a GT_COMMA node tree->ChangeOper(GT_COMMA); tree->gtOp.gtOp2 = op2 = gtNewNothingNode(); // Additionally since we're eliminating the JTRUE // codegen won't like it if op1 is a RELOP of longs, floats or doubles. // So we change it into a GT_COMMA as well. op1->ChangeOper(GT_COMMA); op1->gtType = op1->gtOp.gtOp1->gtType; return tree; } default: break; } noway_assert(oper == tree->gtOper); // If we are in the Valuenum CSE phase then don't morph away anything as these // nodes may have CSE defs/uses in them. // if (!optValnumCSE_phase && (oper != GT_ASG) && (oper != GT_COLON) && !tree->IsList()) { /* Check for op1 as a GT_COMMA with a unconditional throw node */ if (op1 && fgIsCommaThrow(op1, true)) { if ((op1->gtFlags & GTF_COLON_COND) == 0) { /* We can safely throw out the rest of the statements */ fgRemoveRestOfBlock = true; } GenTreePtr throwNode = op1->gtOp.gtOp1; noway_assert(throwNode->gtType == TYP_VOID); if (oper == GT_COMMA) { /* Both tree and op1 are GT_COMMA nodes */ /* Change the tree's op1 to the throw node: op1->gtOp.gtOp1 */ tree->gtOp.gtOp1 = throwNode; return tree; } else if (oper != GT_NOP) { if (genActualType(typ) == genActualType(op1->gtType)) { /* The types match so, return the comma throw node as the new tree */ return op1; } else { if (typ == TYP_VOID) { // Return the throw node return throwNode; } else { GenTreePtr commaOp2 = op1->gtOp.gtOp2; // need type of oper to be same as tree if (typ == TYP_LONG) { commaOp2->ChangeOperConst(GT_CNS_NATIVELONG); commaOp2->gtIntConCommon.SetLngValue(0); /* Change the types of oper and commaOp2 to TYP_LONG */ op1->gtType = commaOp2->gtType = TYP_LONG; } else if (varTypeIsFloating(typ)) { commaOp2->ChangeOperConst(GT_CNS_DBL); commaOp2->gtDblCon.gtDconVal = 0.0; /* Change the types of oper and commaOp2 to TYP_DOUBLE */ op1->gtType = commaOp2->gtType = TYP_DOUBLE; } else { commaOp2->ChangeOperConst(GT_CNS_INT); commaOp2->gtIntConCommon.SetIconValue(0); /* Change the types of oper and commaOp2 to TYP_INT */ op1->gtType = commaOp2->gtType = TYP_INT; } /* Return the GT_COMMA node as the new tree */ return op1; } } } } /* Check for op2 as a GT_COMMA with a unconditional throw */ if (op2 && fgIsCommaThrow(op2, true)) { if ((op2->gtFlags & GTF_COLON_COND) == 0) { /* We can safely throw out the rest of the statements */ fgRemoveRestOfBlock = true; } // If op1 has no side-effects if ((op1->gtFlags & GTF_ALL_EFFECT) == 0) { // If tree is an asg node if (tree->OperIsAssignment()) { /* Return the throw node as the new tree */ return op2->gtOp.gtOp1; } if (tree->OperGet() == GT_ARR_BOUNDS_CHECK) { /* Return the throw node as the new tree */ return op2->gtOp.gtOp1; } // If tree is a comma node if (tree->OperGet() == GT_COMMA) { /* Return the throw node as the new tree */ return op2->gtOp.gtOp1; } /* for the shift nodes the type of op2 can differ from the tree type */ if ((typ == TYP_LONG) && (genActualType(op2->gtType) == TYP_INT)) { noway_assert((oper == GT_LSH) || (oper == GT_RSH) || (oper == GT_RSZ) || (oper == GT_ROL) || (oper == GT_ROR)); GenTreePtr commaOp2 = op2->gtOp.gtOp2; commaOp2->ChangeOperConst(GT_CNS_NATIVELONG); commaOp2->gtIntConCommon.SetLngValue(0); /* Change the types of oper and commaOp2 to TYP_LONG */ op2->gtType = commaOp2->gtType = TYP_LONG; } if ((genActualType(typ) == TYP_INT) && (genActualType(op2->gtType) == TYP_LONG || varTypeIsFloating(op2->TypeGet()))) { // An example case is comparison (say GT_GT) of two longs or floating point values. GenTreePtr commaOp2 = op2->gtOp.gtOp2; commaOp2->ChangeOperConst(GT_CNS_INT); commaOp2->gtIntCon.gtIconVal = 0; /* Change the types of oper and commaOp2 to TYP_INT */ op2->gtType = commaOp2->gtType = TYP_INT; } if ((typ == TYP_BYREF) && (genActualType(op2->gtType) == TYP_I_IMPL)) { noway_assert(tree->OperGet() == GT_ADD); GenTreePtr commaOp2 = op2->gtOp.gtOp2; commaOp2->ChangeOperConst(GT_CNS_INT); commaOp2->gtIntCon.gtIconVal = 0; /* Change the types of oper and commaOp2 to TYP_BYREF */ op2->gtType = commaOp2->gtType = TYP_BYREF; } /* types should now match */ noway_assert( (genActualType(typ) == genActualType(op2->gtType))); /* Return the GT_COMMA node as the new tree */ return op2; } } } /*------------------------------------------------------------------------- * Optional morphing is done if tree transformations is permitted */ if ((opts.compFlags & CLFLG_TREETRANS) == 0) return tree; tree = fgMorphSmpOpOptional(tree->AsOp()); } // extra scope for gcc workaround return tree; } #ifdef _PREFAST_ #pragma warning(pop) #endif GenTree* Compiler::fgMorphSmpOpOptional(GenTreeOp* tree) { genTreeOps oper = tree->gtOper; GenTree* op1 = tree->gtOp1; GenTree* op2 = tree->gtOp2; var_types typ = tree->TypeGet(); if (GenTree::OperIsCommutative(oper)) { /* Swap the operands so that the more expensive one is 'op1' */ if (tree->gtFlags & GTF_REVERSE_OPS) { tree->gtOp1 = op2; tree->gtOp2 = op1; op2 = op1; op1 = tree->gtOp1; tree->gtFlags &= ~GTF_REVERSE_OPS; } if (oper == op2->gtOper) { /* Reorder nested operators at the same precedence level to be left-recursive. For example, change "(a+(b+c))" to the equivalent expression "((a+b)+c)". */ /* Things are handled differently for floating-point operators */ if (!varTypeIsFloating(tree->TypeGet())) { fgMoveOpsLeft(tree); op1 = tree->gtOp1; op2 = tree->gtOp2; } } } #if REARRANGE_ADDS /* Change "((x+icon)+y)" to "((x+y)+icon)" Don't reorder floating-point operations */ if ((oper == GT_ADD) && !tree->gtOverflow() && (op1->gtOper == GT_ADD) && ! op1->gtOverflow() && varTypeIsIntegralOrI(typ)) { GenTreePtr ad2 = op1->gtOp.gtOp2; if (op2->OperIsConst() == 0 && ad2->OperIsConst() != 0) { //This takes // + (tree) // / \ // / \ // / \ // + (op1) op2 // / \ // \ // ad2 // // And it swaps ad2 and op2. If (op2) is varTypeIsGC, then this implies that (tree) is // varTypeIsGC. If (op1) is not, then when we swap (ad2) and (op2), then we have a TYP_INT node // (op1) with a child that is varTypeIsGC. If we encounter that situation, make (op1) the same // type as (tree). // // Also, if (ad2) is varTypeIsGC then (tree) must also be (since op1 is), so no fixing is // necessary if (varTypeIsGC(op2->TypeGet())) { noway_assert(varTypeIsGC(typ)); op1->gtType = typ; } tree->gtOp2 = ad2; op1 ->gtOp.gtOp2 = op2; op1->gtFlags |= op2->gtFlags & GTF_ALL_EFFECT; op2 = tree->gtOp2; } } #endif /*------------------------------------------------------------------------- * Perform optional oper-specific postorder morphing */ switch (oper) { genTreeOps cmop; bool dstIsSafeLclVar; case GT_ASG: /* We'll convert "a = a <op> x" into "a <op>= x" */ /* and also "a = x <op> a" into "a <op>= x" for communative ops */ #if !LONG_ASG_OPS if (typ == TYP_LONG) break; #endif /* Make sure we're allowed to do this */ if (optValnumCSE_phase) { // It is not safe to reorder/delete CSE's break; } /* Are we assigning to a GT_LCL_VAR ? */ dstIsSafeLclVar = (op1->gtOper == GT_LCL_VAR); /* If we have a GT_LCL_VAR, then is the address taken? */ if (dstIsSafeLclVar) { unsigned lclNum = op1->gtLclVarCommon.gtLclNum; LclVarDsc * varDsc = lvaTable + lclNum; noway_assert(lclNum < lvaCount); /* Is the address taken? */ if (varDsc->lvAddrExposed) { dstIsSafeLclVar = false; } else if (op2->gtFlags & GTF_ASG) { break; } } if (!dstIsSafeLclVar) { if (op2->gtFlags & GTF_ASG) break; if ((op2->gtFlags & GTF_CALL) && (op1->gtFlags & GTF_ALL_EFFECT)) break; } /* Special case: a cast that can be thrown away */ if (op1->gtOper == GT_IND && op2->gtOper == GT_CAST && !op2->gtOverflow() ) { var_types srct; var_types cast; var_types dstt; srct = op2->gtCast.CastOp()->TypeGet(); cast = (var_types) op2->CastToType(); dstt = op1->TypeGet(); /* Make sure these are all ints and precision is not lost */ if (cast >= dstt && dstt <= TYP_INT && srct <= TYP_INT) op2 = tree->gtOp2 = op2->gtCast.CastOp(); } /* Make sure we have the operator range right */ noway_assert(GT_SUB == GT_ADD + 1); noway_assert(GT_MUL == GT_ADD + 2); noway_assert(GT_DIV == GT_ADD + 3); noway_assert(GT_MOD == GT_ADD + 4); noway_assert(GT_UDIV== GT_ADD + 5); noway_assert(GT_UMOD== GT_ADD + 6); noway_assert(GT_OR == GT_ADD + 7); noway_assert(GT_XOR == GT_ADD + 8); noway_assert(GT_AND == GT_ADD + 9); noway_assert(GT_LSH == GT_ADD + 10); noway_assert(GT_RSH == GT_ADD + 11); noway_assert(GT_RSZ == GT_ADD + 12); /* Check for a suitable operator on the RHS */ cmop = op2->OperGet(); switch (cmop) { case GT_NEG: // GT_CHS only supported for integer types if ( varTypeIsFloating(tree->TypeGet())) break; goto ASG_OP; case GT_MUL: // GT_ASG_MUL only supported for floating point types if (!varTypeIsFloating(tree->TypeGet())) break; __fallthrough; case GT_ADD: case GT_SUB: if (op2->gtOverflow()) { /* Disable folding into "<op>=" if the result can be visible to anyone as <op> may throw an exception and the assignment should not proceed We are safe with an assignment to a local variables */ if (compCurBB->hasTryIndex()) break; if (!dstIsSafeLclVar) break; } #ifndef _TARGET_AMD64_ // This is hard for byte-operations as we need to make // sure both operands are in RBM_BYTE_REGS. if (varTypeIsByte(op2->TypeGet())) break; #endif // _TARGET_AMD64_ goto ASG_OP; case GT_DIV: case GT_UDIV: // GT_ASG_DIV only supported for floating point types if (!varTypeIsFloating(tree->TypeGet())) break; case GT_LSH: case GT_RSH: case GT_RSZ: #if LONG_ASG_OPS if (typ == TYP_LONG) break; #endif case GT_OR: case GT_XOR: case GT_AND: #if LONG_ASG_OPS /* TODO: allow non-const long assignment operators */ if (typ == TYP_LONG && op2->gtOp.gtOp2->gtOper != GT_CNS_LNG) break; #endif ASG_OP: { bool bReverse = false; bool bAsgOpFoldable = fgShouldCreateAssignOp(tree, &bReverse); if (bAsgOpFoldable) { if (bReverse) { // We will transform this from "a = x <op> a" to "a <op>= x" // so we can now destroy the duplicate "a" DEBUG_DESTROY_NODE(op2->gtOp.gtOp2); op2->gtOp.gtOp2 = op2->gtOp.gtOp1; } /* Special case: "x |= -1" and "x &= 0" */ if (cmop == GT_AND || cmop == GT_OR) { if (op2->gtOp.gtOp2->IsCnsIntOrI()) { ssize_t icon = op2->gtOp.gtOp2->gtIntCon.gtIconVal; noway_assert(typ <= TYP_UINT); if ((cmop == GT_AND && icon == 0) || (cmop == GT_OR && icon == -1)) { /* Simply change to an assignment */ tree->gtOp2 = op2->gtOp.gtOp2; break; } } } if (cmop == GT_NEG) { /* This is "x = -x;", use the flipsign operator */ tree->ChangeOper (GT_CHS); if (op1->gtOper == GT_LCL_VAR) op1->gtFlags |= GTF_VAR_USEASG; tree->gtOp2 = gtNewIconNode(0, op1->TypeGet()); break; } if (cmop == GT_RSH && varTypeIsSmall(op1->TypeGet()) && varTypeIsUnsigned(op1->TypeGet())) { // Changing from x = x op y to x op= y when x is a small integer type // makes the op size smaller (originally the op size was 32 bits, after // sign or zero extension of x, and there is an implicit truncation in the // assignment). // This is ok in most cases because the upper bits were // lost when assigning the op result to a small type var, // but it may not be ok for the right shift operation where the higher bits // could be shifted into the lower bits and preserved. // Signed right shift of signed x still works (i.e. (sbyte)((int)(sbyte)x >>signed y) == (sbyte)x >>signed y)) // as do unsigned right shift ((ubyte)((int)(ubyte)x >>unsigned y) == (ubyte)x >>unsigned y), but // signed right shift of an unigned small type may give the wrong result: // e.g. (ubyte)((int)(ubyte)0xf0 >>signed 4) == 0x0f, // but (ubyte)0xf0 >>signed 4 == 0xff which is incorrect. // The result becomes correct if we use >>unsigned instead of >>signed. noway_assert(op1->TypeGet() == op2->gtOp.gtOp1->TypeGet()); cmop = GT_RSZ; } /* Replace with an assignment operator */ noway_assert(GT_ADD - GT_ADD == GT_ASG_ADD - GT_ASG_ADD); noway_assert(GT_SUB - GT_ADD == GT_ASG_SUB - GT_ASG_ADD); noway_assert(GT_OR - GT_ADD == GT_ASG_OR - GT_ASG_ADD); noway_assert(GT_XOR - GT_ADD == GT_ASG_XOR - GT_ASG_ADD); noway_assert(GT_AND - GT_ADD == GT_ASG_AND - GT_ASG_ADD); noway_assert(GT_LSH - GT_ADD == GT_ASG_LSH - GT_ASG_ADD); noway_assert(GT_RSH - GT_ADD == GT_ASG_RSH - GT_ASG_ADD); noway_assert(GT_RSZ - GT_ADD == GT_ASG_RSZ - GT_ASG_ADD); tree->SetOper((genTreeOps)(cmop - GT_ADD + GT_ASG_ADD)); tree->gtOp2 = op2->gtOp.gtOp2; /* Propagate GTF_OVERFLOW */ if (op2->gtOverflowEx()) { tree->gtType = op2->gtType; tree->gtFlags |= (op2->gtFlags & (GTF_OVERFLOW|GTF_EXCEPT|GTF_UNSIGNED)); } #if FEATURE_SET_FLAGS /* Propagate GTF_SET_FLAGS */ if (op2->gtSetFlags()) { tree->gtRequestSetFlags(); } #endif // FEATURE_SET_FLAGS DEBUG_DESTROY_NODE(op2); op2 = tree->gtOp2; /* The target is used as well as being defined */ if (op1->OperIsLocal()) op1->gtFlags |= GTF_VAR_USEASG; #if CPU_HAS_FP_SUPPORT /* Check for the special case "x += y * x;" */ // GT_ASG_MUL only supported for floating point types if (cmop != GT_ADD && cmop != GT_SUB) break; if (op2->gtOper == GT_MUL && varTypeIsFloating(tree->TypeGet())) { if (GenTree::Compare(op1, op2->gtOp.gtOp1)) { /* Change "x += x * y" into "x *= (y + 1)" */ op2 = op2->gtOp.gtOp2; } else if (GenTree::Compare(op1, op2->gtOp.gtOp2)) { /* Change "x += y * x" into "x *= (y + 1)" */ op2 = op2->gtOp.gtOp1; } else break; op1 = gtNewDconNode(1.0); /* Now make the "*=" node */ if (cmop == GT_ADD) { /* Change "x += x * y" into "x *= (y + 1)" */ tree->gtOp2 = op2 = gtNewOperNode(GT_ADD, tree->TypeGet(), op2, op1); } else { /* Change "x -= x * y" into "x *= (1 - y)" */ noway_assert(cmop == GT_SUB); tree->gtOp2 = op2 = gtNewOperNode(GT_SUB, tree->TypeGet(), op1, op2); } tree->ChangeOper(GT_ASG_MUL); } #endif // CPU_HAS_FP_SUPPORT } } break; case GT_NOT: /* Is the destination identical to the first RHS sub-operand? */ if (GenTree::Compare(op1, op2->gtOp.gtOp1)) { /* This is "x = ~x" which is the same as "x ^= -1" * Transform the node into a GT_ASG_XOR */ noway_assert(genActualType(typ) == TYP_INT || genActualType(typ) == TYP_LONG); op2->gtOp.gtOp2 = (genActualType(typ) == TYP_INT) ? gtNewIconNode(-1) : gtNewLconNode(-1); cmop = GT_XOR; goto ASG_OP; } break; default: break; } break; case GT_MUL: /* Check for the case "(val + icon) * icon" */ if (op2->gtOper == GT_CNS_INT && op1->gtOper == GT_ADD) { GenTreePtr add = op1->gtOp.gtOp2; if (add->IsCnsIntOrI() && (op2->GetScaleIndexMul() != 0)) { if (tree->gtOverflow() || op1->gtOverflow()) { break; } ssize_t imul = op2->gtIntCon.gtIconVal; ssize_t iadd = add->gtIntCon.gtIconVal; /* Change '(val + iadd) * imul' -> '(val * imul) + (iadd * imul)' */ oper = GT_ADD; tree->ChangeOper(oper); op2->gtIntCon.gtIconVal = iadd * imul; op1->ChangeOper(GT_MUL); add->gtIntCon.gtIconVal = imul; #ifdef _TARGET_64BIT_ if (add->gtType == TYP_INT) { // we need to properly re-sign-extend or truncate after multiplying two int constants above add->AsIntCon()->TruncateOrSignExtend32(); } #endif //_TARGET_64BIT_ } } break; case GT_DIV: /* For "val / 1", just return "val" */ if ((op2->gtOper == GT_CNS_INT) && (op2->gtIntConCommon.IconValue() == 1)) { DEBUG_DESTROY_NODE(tree); return op1; } // Do this for "long" constants as well as ints. else if ((op2->gtOper == GT_CNS_LNG) && (op2->gtIntConCommon.LngValue() == 1)) { DEBUG_DESTROY_NODE(tree); return op1; } break; case GT_LSH: /* Check for the case "(val + icon) << icon" */ if (op2->IsCnsIntOrI() && op1->gtOper == GT_ADD && !op1->gtOverflow()) { GenTreePtr cns = op1->gtOp.gtOp2; if (cns->IsCnsIntOrI() && (op2->GetScaleIndexShf() != 0)) { ssize_t ishf = op2->gtIntConCommon.IconValue(); ssize_t iadd = cns->gtIntConCommon.IconValue(); // printf("Changing '(val+icon1)<<icon2' into '(val<<icon2+icon1<<icon2)'\n"); /* Change "(val + iadd) << ishf" into "(val<<ishf + iadd<<ishf)" */ tree->ChangeOper(GT_ADD); ssize_t result = iadd << ishf; op2->gtIntConCommon.SetIconValue(result); #ifdef _TARGET_64BIT_ if (op1->gtType == TYP_INT) { op2->AsIntCon()->TruncateOrSignExtend32(); } #endif // _TARGET_64BIT_ // we are reusing the shift amount node here, but the type we want is that of the shift result op2->gtType = op1->gtType; if (cns->gtOper == GT_CNS_INT && cns->gtIntCon.gtFieldSeq != nullptr && cns->gtIntCon.gtFieldSeq->IsConstantIndexFieldSeq()) { assert(cns->gtIntCon.gtFieldSeq->m_next == nullptr); op2->gtIntCon.gtFieldSeq = cns->gtIntCon.gtFieldSeq; } op1->ChangeOper(GT_LSH); cns->gtIntConCommon.SetIconValue(ishf); } } break; case GT_XOR: if (!optValnumCSE_phase) { /* "x ^ -1" is "~x" */ if ((op2->gtOper == GT_CNS_INT) && (op2->gtIntConCommon.IconValue() == -1)) { tree->ChangeOper(GT_NOT); tree->gtOp2 = NULL; DEBUG_DESTROY_NODE(op2); } else if ((op2->gtOper == GT_CNS_LNG) && (op2->gtIntConCommon.LngValue() == -1)) { tree->ChangeOper(GT_NOT); tree->gtOp2 = NULL; DEBUG_DESTROY_NODE(op2); } else if ((op2->gtOper == GT_CNS_INT) && (op2->gtIntConCommon.IconValue() == 1) && op1->OperIsCompare()) { /* "binaryVal ^ 1" is "!binaryVal" */ gtReverseCond(op1); DEBUG_DESTROY_NODE(op2); DEBUG_DESTROY_NODE(tree); return op1; } } break; case GT_INITBLK: return fgMorphInitBlock(tree); break; case GT_COPYOBJ: case GT_COPYBLK: return fgMorphCopyBlock(tree); break; default: break; } return tree; } // code to generate a magic number and shift amount for the magic number division // optimization. This code is previously from UTC where it notes it was taken from // _The_PowerPC_Compiler_Writer's_Guide_, pages 57-58. // The paper it is based on is "Division by invariant integers using multiplication" // by Torbjorn Granlund and Peter L. Montgomery in PLDI 94 template <typename T> T GetSignedMagicNumberForDivide(T denom, int *shift /*out*/) { // static SMAG smag; const int bits = sizeof(T) * 8; const int bits_minus_1 = bits - 1; typedef typename jitstd::make_unsigned<T>::type UT; const UT two_nminus1 = UT(1) << bits_minus_1; int p; UT absDenom; UT absNc; UT delta; UT q1; UT r1; UT r2; UT q2; UT t; T result_magic; int result_shift; int iters = 0; absDenom = abs(denom); t = two_nminus1 + ((unsigned int)denom >> 31); absNc = t - 1 - (t % absDenom); // absolute value of nc p = bits_minus_1; // initialize p q1 = two_nminus1 / absNc; // initialize q1 = 2^p / abs(nc) r1 = two_nminus1 - (q1 * absNc); // initialize r1 = rem(2^p, abs(nc)) q2 = two_nminus1 / absDenom; // initialize q1 = 2^p / abs(denom) r2 = two_nminus1 - (q2 * absDenom); // initialize r1 = rem(2^p, abs(denom)) do { iters++; p++; q1 *= 2; // update q1 = 2^p / abs(nc) r1 *= 2; // update r1 = rem(2^p / abs(nc)) if (r1 >= absNc) { // must be unsigned comparison q1++; r1 -= absNc; } q2 *= 2; // update q2 = 2^p / abs(denom) r2 *= 2; // update r2 = rem(2^p / abs(denom)) if (r2 >= absDenom) { // must be unsigned comparison q2++; r2 -= absDenom; } delta = absDenom - r2; } while (q1 < delta || (q1 == delta && r1 == 0)); result_magic = q2 + 1; // resulting magic number if (denom < 0) { result_magic = -result_magic; } *shift = p - bits; // resulting shift return result_magic; } bool Compiler::fgShouldUseMagicNumberDivide(GenTreeOp* tree) { #ifdef _TARGET_ARM64_ // TODO-ARM64-NYI: We don't have a 'mulHi' implementation yet for ARM64 return false; #else // During the optOptimizeValnumCSEs phase we can call fgMorph and when we do, // if this method returns true we will introduce a new LclVar and // a couple of new GenTree nodes, including an assignment to the new LclVar. // None of these new GenTree nodes will have valid ValueNumbers. // That is an invalid state for a GenTree node during the optOptimizeValnumCSEs phase. // // Also during optAssertionProp when extracting side effects we can assert // during gtBuildCommaList if we have one tree that has Value Numbers // and another one that does not. // if (!fgGlobalMorph) { // We only perform the Magic Number Divide optimization during // the initial global morph phase return false; } if (tree->gtFlags & GTF_OVERFLOW) return false; if (tree->gtOp2->gtOper != GT_CNS_INT && tree->gtOp2->gtOper != GT_CNS_LNG) return false; ssize_t cons = tree->gtOp2->gtIntConCommon.IconValue(); if (cons == 0 || cons == -1 || cons == 1) return false; // codegen will expand these if (isPow2(cons)) return false; // someone else will fold this away, so don't make it complicated for them if (tree->gtOp1->IsCnsIntOrI()) return false; // There is no technical barrier to handling unsigned, however it is quite rare // and more work to support and test if (tree->gtFlags & GTF_UNSIGNED) return false; return true; #endif } // transform x%c -> x-((x/c)*c) GenTree* Compiler::fgMorphModByConst(GenTreeOp* tree) { assert(fgShouldUseMagicNumberDivide(tree)); var_types type = tree->gtType; GenTree* cns = tree->gtOp2; GenTree* numerator = fgMakeMultiUse(&tree->gtOp1); tree->SetOper(GT_DIV); GenTree* mul = gtNewOperNode(GT_MUL, type, tree, gtCloneExpr(cns)); GenTree* sub = gtNewOperNode(GT_SUB, type, numerator, mul); #ifdef DEBUG sub->gtFlags |= GTF_MORPHED; #endif return sub; } // For ARM64 we don't have a remainder instruction, // The architecture manual suggests the following transformation to // generate code for such operator: // // a % b = a - (a / b) * b; // // This method will produce the above expression in 'a' and 'b' are // leaf nodes, otherwise, if any of them is not a leaf it will spill // its value into a temporary variable, an example: // (x * 2 - 1) % (y + 1) -> t1 - (t2 * ( comma(t1 = x * 2 - 1, t1) / comma(t2 = y + 1, t2) ) ) // GenTree* Compiler::fgMorphModToSubMulDiv(GenTreeOp* tree) { #ifndef _TARGET_ARM64_ assert(!"This should only be called for ARM64"); #endif if (tree->OperGet() == GT_MOD) { tree->SetOper(GT_DIV); } else if (tree->OperGet() == GT_UMOD) { tree->SetOper(GT_UDIV); } else { noway_assert(!"Illegal gtOper in fgMorphModToSubMulDiv"); } var_types type = tree->gtType; GenTree* denominator = tree->gtOp2; GenTree* numerator = tree->gtOp1; if (!numerator->OperIsLeaf()) { numerator = fgMakeMultiUse(&tree->gtOp1); } if (!denominator->OperIsLeaf()) { denominator = fgMakeMultiUse(&tree->gtOp2); } GenTree* mul = gtNewOperNode(GT_MUL, type, tree, gtCloneExpr(denominator)); GenTree* sub = gtNewOperNode(GT_SUB, type, gtCloneExpr(numerator), mul); #ifdef DEBUG sub->gtFlags |= GTF_MORPHED; #endif return sub; } // Turn a division by a constant into a multiplication by constant + some adjustments // see comments on GetSignedMagicNumberForDivide for source of this algorithm. // returns: the transformed tree GenTree* Compiler::fgMorphDivByConst(GenTreeOp* tree) { assert(fgShouldUseMagicNumberDivide(tree)); JITDUMP("doing magic number divide optimization\n"); int64_t denominator = tree->gtOp2->gtIntConCommon.IconValue(); int64_t magic; int shift; var_types type = tree->gtType; if (tree->gtType == TYP_INT) { magic = GetSignedMagicNumberForDivide<int32_t>((int32_t) denominator, &shift); } else { magic = GetSignedMagicNumberForDivide<int64_t>((int64_t) denominator, &shift); } GenTree* numerator = nullptr; // If signs of the denominator and magic number don't match, // we will need to use the numerator again. if (signum(denominator) != signum(magic)) { numerator = fgMakeMultiUse(&tree->gtOp1); tree->gtFlags |= GTF_ASG; } if (type == TYP_LONG) tree->gtOp2->gtIntConCommon.SetLngValue(magic); else tree->gtOp2->gtIntConCommon.SetIconValue((ssize_t)magic); tree->SetOper(GT_MULHI); GenTree* t = tree; GenTree* mulresult = tree; JITDUMP("Multiply Result:\n"); DISPTREE(mulresult); GenTree *adjusted = mulresult; if (denominator > 0 && magic < 0) { // add the numerator back in adjusted = gtNewOperNode(GT_ADD, type, mulresult, numerator); } else if (denominator < 0 && magic > 0) { // subtract the numerator off adjusted = gtNewOperNode(GT_SUB, type, mulresult, numerator); } else { adjusted = mulresult; } GenTree* result1 = adjusted; if (shift != 0) { result1 = gtNewOperNode(GT_RSH, type, adjusted, gtNewIconNode(shift, TYP_INT)); } GenTree* secondClone = fgMakeMultiUse(&result1); GenTree* result2 = gtNewOperNode(GT_RSZ, type, secondClone, gtNewIconNode(genTypeSize(type) * 8 - 1, type)); GenTree* result = gtNewOperNode(GT_ADD, type, result1, result2); JITDUMP("Final Magic Number divide:\n"); DISPTREE(result); #ifdef DEBUG result->gtFlags |= GTF_MORPHED; #endif return result; } //------------------------------------------------------------------------------ // fgOperIsBitwiseRotationRoot : Check if the operation can be a root of a bitwise rotation tree. // // // Arguments: // oper - Operation to check // // Return Value: // True if the operation can be a root of a bitwise rotation tree; false otherwise. bool Compiler::fgOperIsBitwiseRotationRoot(genTreeOps oper) { return (oper == GT_OR) || (oper == GT_XOR); } //------------------------------------------------------------------------------ // fgRecognizeAndMorphBitwiseRotation : Check if the tree represents a left or right rotation. If so, return // an equivalent GT_ROL or GT_ROR tree; otherwise, return the original tree. // // Arguments: // tree - tree to check for a rotation pattern // // Return Value: // An equivalent GT_ROL or GT_ROR tree if a pattern is found; original tree otherwise. // // Assumption: // The input is a GT_OR or a GT_XOR tree. GenTreePtr Compiler::fgRecognizeAndMorphBitwiseRotation(GenTreePtr tree) { #ifndef LEGACY_BACKEND // // Check for a rotation pattern, e.g., // // OR ROL // / \ / \ // LSH RSZ -> x y // / \ / \ // x AND x AND // / \ / \ // y 31 ADD 31 // / \ // NEG 32 // | // y // The patterns recognized: // (x << (y & M)) op (x >>> ((-y + N) & M)) // (x >>> ((-y + N) & M)) op (x << (y & M)) // // (x << y) op (x >>> (-y + N)) // (x >> > (-y + N)) op (x << y) // // (x >>> (y & M)) op (x << ((-y + N) & M)) // (x << ((-y + N) & M)) op (x >>> (y & M)) // // (x >>> y) op (x << (-y + N)) // (x << (-y + N)) op (x >>> y) // // (x << c1) op (x >>> c2) // (x >>> c1) op (x << c2) // // where // c1 and c2 are const // c1 + c2 == bitsize(x) // N == bitsize(x) // M is const // M & (N - 1) == N - 1 // op is either | or ^ if (((tree->gtFlags & GTF_PERSISTENT_SIDE_EFFECTS) != 0) || ((tree->gtFlags & GTF_ORDER_SIDEEFF) != 0)) { // We can't do anything if the tree has assignments, calls, or volatile // reads. Note that we allow GTF_EXCEPT side effect since any exceptions // thrown by the original tree will be thrown by the transformed tree as well. return tree; } genTreeOps oper = tree->OperGet(); assert(fgOperIsBitwiseRotationRoot(oper)); // Check if we have an LSH on one side of the OR and an RSZ on the other side. GenTreePtr op1 = tree->gtGetOp1(); GenTreePtr op2 = tree->gtGetOp2(); GenTreePtr leftShiftTree = nullptr; GenTreePtr rightShiftTree = nullptr; if ((op1->OperGet() == GT_LSH) && (op2->OperGet() == GT_RSZ)) { leftShiftTree = op1; rightShiftTree = op2; } else if ((op1->OperGet() == GT_RSZ) && (op2->OperGet() == GT_LSH)) { leftShiftTree = op2; rightShiftTree = op1; } else { return tree; } // Check if the trees representing the value to shift are identical. // We already checked that there are no side effects above. if (GenTree::Compare(leftShiftTree->gtGetOp1(), rightShiftTree->gtGetOp1())) { GenTreePtr rotatedValue = leftShiftTree->gtGetOp1(); var_types rotatedValueActualType = genActualType(rotatedValue->gtType); ssize_t rotatedValueBitSize = genTypeSize(rotatedValueActualType) * 8; noway_assert((rotatedValueBitSize == 32) || (rotatedValueBitSize == 64)); GenTreePtr leftShiftIndex = leftShiftTree->gtGetOp2(); GenTreePtr rightShiftIndex = rightShiftTree->gtGetOp2(); // The shift index may be masked. At least (rotatedValueBitSize - 1) lower bits // shouldn't be masked for the transformation to be valid. If additional // higher bits are not masked, the transformation is still valid since the result // of MSIL shift instructions is unspecified if the shift amount is greater or equal // than the width of the value being shifted. ssize_t minimalMask = rotatedValueBitSize - 1; ssize_t leftShiftMask = -1; ssize_t rightShiftMask = -1; if ((leftShiftIndex->OperGet() == GT_AND)) { if (leftShiftIndex->gtGetOp2()->IsCnsIntOrI()) { leftShiftMask = leftShiftIndex->gtGetOp2()->gtIntCon.gtIconVal; leftShiftIndex = leftShiftIndex->gtGetOp1(); } else { return tree; } } if ((rightShiftIndex->OperGet() == GT_AND)) { if (rightShiftIndex->gtGetOp2()->IsCnsIntOrI()) { rightShiftMask = rightShiftIndex->gtGetOp2()->gtIntCon.gtIconVal; rightShiftIndex = rightShiftIndex->gtGetOp1(); } else { return tree; } } if (((minimalMask & leftShiftMask) != minimalMask) || ((minimalMask & rightShiftMask) != minimalMask)) { // The shift index is overmasked, e.g., we have // something like (x << y & 15) or // (x >> (32 - y) & 15 with 32 bit x. // The transformation is not valid. return tree; } GenTreePtr shiftIndexWithAdd = nullptr; GenTreePtr shiftIndexWithoutAdd = nullptr; genTreeOps rotateOp = GT_NONE; GenTreePtr rotateIndex = nullptr; if (leftShiftIndex->OperGet() == GT_ADD) { shiftIndexWithAdd = leftShiftIndex; shiftIndexWithoutAdd = rightShiftIndex; rotateOp = GT_ROR; } else if (rightShiftIndex->OperGet() == GT_ADD) { shiftIndexWithAdd = rightShiftIndex; shiftIndexWithoutAdd = leftShiftIndex; rotateOp = GT_ROL; } if (shiftIndexWithAdd != nullptr) { if (shiftIndexWithAdd->gtGetOp2()->IsCnsIntOrI()) { if (shiftIndexWithAdd->gtGetOp2()->gtIntCon.gtIconVal == rotatedValueBitSize) { if (shiftIndexWithAdd->gtGetOp1()->OperGet() == GT_NEG) { if (GenTree::Compare(shiftIndexWithAdd->gtGetOp1()->gtGetOp1(), shiftIndexWithoutAdd)) { // We found one of these patterns: // (x << (y & M)) | (x >>> ((-y + N) & M)) // (x << y) | (x >>> (-y + N)) // (x >>> (y & M)) | (x << ((-y + N) & M)) // (x >>> y) | (x << (-y + N)) // where N == bitsize(x), M is const, and // M & (N - 1) == N - 1 #ifndef _TARGET_64BIT_ if (!shiftIndexWithoutAdd->IsCnsIntOrI() && (rotatedValueBitSize == 64)) { // TODO: we need to handle variable-sized long shifts specially on x86. // GT_LSH, GT_RSH, and GT_RSZ have helpers for this case. We may need // to add helpers for GT_ROL and GT_ROR. NYI("Rotation of a long value by variable amount"); } #endif rotateIndex = shiftIndexWithoutAdd; } } } } } else if ((leftShiftIndex->IsCnsIntOrI() && rightShiftIndex->IsCnsIntOrI())) { if (leftShiftIndex->gtIntCon.gtIconVal + rightShiftIndex->gtIntCon.gtIconVal == rotatedValueBitSize) { // We found this pattern: // (x << c1) | (x >>> c2) // where c1 and c2 are const and c1 + c2 == bitsize(x) rotateOp = GT_ROL; rotateIndex = leftShiftIndex; } } if (rotateIndex != nullptr) { noway_assert((rotateOp == GT_ROL) || (rotateOp == GT_ROR)); unsigned inputTreeEffects = tree->gtFlags & GTF_ALL_EFFECT; // We can use the same tree only during global morph; reusing the tree in a later morph // may invalidate value numbers. if (fgGlobalMorph) { tree->gtOp.gtOp1 = rotatedValue; tree->gtOp.gtOp2 = rotateIndex; tree->ChangeOper(rotateOp); noway_assert(inputTreeEffects == ((rotatedValue->gtFlags | rotateIndex->gtFlags) & GTF_ALL_EFFECT)); } else { tree = gtNewOperNode(rotateOp, rotatedValueActualType, rotatedValue, rotateIndex); noway_assert(inputTreeEffects == (tree->gtFlags & GTF_ALL_EFFECT)); } return tree; } } #endif //LEGACY_BACKEND return tree; } #if !CPU_HAS_FP_SUPPORT GenTreePtr Compiler::fgMorphToEmulatedFP(GenTreePtr tree) { genTreeOps oper = tree->OperGet(); var_types typ = tree->TypeGet(); GenTreePtr op1 = tree->gtOp.gtOp1; GenTreePtr op2 = tree->gtGetOp2(); /* We have to use helper calls for all FP operations: FP operators that operate on FP values casts to and from FP comparisons of FP values */ if (varTypeIsFloating(typ) || (op1 && varTypeIsFloating(op1->TypeGet()))) { int helper; GenTreePtr args; size_t argc = genTypeStSz(typ); /* Not all FP operations need helper calls */ switch (oper) { case GT_ASG: case GT_IND: case GT_LIST: case GT_ADDR: case GT_COMMA: return tree; } #ifdef DEBUG /* If the result isn't FP, it better be a compare or cast */ if (!(varTypeIsFloating(typ) || tree->OperIsCompare() || oper == GT_CAST)) gtDispTree(tree); noway_assert(varTypeIsFloating(typ) || tree->OperIsCompare() || oper == GT_CAST); #endif /* Keep track of how many arguments we're passing */ fgPtrArgCntCur += argc; /* Is this a binary operator? */ if (op2) { /* Add the second operand to the argument count */ fgPtrArgCntCur += argc; argc *= 2; /* What kind of an operator do we have? */ switch (oper) { case GT_ADD: helper = CPX_R4_ADD; break; case GT_SUB: helper = CPX_R4_SUB; break; case GT_MUL: helper = CPX_R4_MUL; break; case GT_DIV: helper = CPX_R4_DIV; break; // case GT_MOD: helper = CPX_R4_REM; break; case GT_EQ : helper = CPX_R4_EQ ; break; case GT_NE : helper = CPX_R4_NE ; break; case GT_LT : helper = CPX_R4_LT ; break; case GT_LE : helper = CPX_R4_LE ; break; case GT_GE : helper = CPX_R4_GE ; break; case GT_GT : helper = CPX_R4_GT ; break; default: #ifdef DEBUG gtDispTree(tree); #endif noway_assert(!"unexpected FP binary op"); break; } args = gtNewArgList(tree->gtOp.gtOp2, tree->gtOp.gtOp1); } else { switch (oper) { case GT_RETURN: return tree; case GT_CAST: noway_assert(!"FP cast"); case GT_NEG: helper = CPX_R4_NEG; break; default: #ifdef DEBUG gtDispTree(tree); #endif noway_assert(!"unexpected FP unary op"); break; } args = gtNewArgList(tree->gtOp.gtOp1); } /* If we have double result/operands, modify the helper */ if (typ == TYP_DOUBLE) { noway_assert(CPX_R4_NEG+1 == CPX_R8_NEG); noway_assert(CPX_R4_ADD+1 == CPX_R8_ADD); noway_assert(CPX_R4_SUB+1 == CPX_R8_SUB); noway_assert(CPX_R4_MUL+1 == CPX_R8_MUL); noway_assert(CPX_R4_DIV+1 == CPX_R8_DIV); helper++; } else { noway_assert(tree->OperIsCompare()); noway_assert(CPX_R4_EQ+1 == CPX_R8_EQ); noway_assert(CPX_R4_NE+1 == CPX_R8_NE); noway_assert(CPX_R4_LT+1 == CPX_R8_LT); noway_assert(CPX_R4_LE+1 == CPX_R8_LE); noway_assert(CPX_R4_GE+1 == CPX_R8_GE); noway_assert(CPX_R4_GT+1 == CPX_R8_GT); } tree = fgMorphIntoHelperCall(tree, helper, args); if (fgPtrArgCntMax < fgPtrArgCntCur) fgPtrArgCntMax = fgPtrArgCntCur; fgPtrArgCntCur -= argc; return tree; case GT_RETURN: if (op1) { if (compCurBB == genReturnBB) { /* This is the 'exitCrit' call at the exit label */ noway_assert(op1->gtType == TYP_VOID); noway_assert(op2 == 0); tree->gtOp.gtOp1 = op1 = fgMorphTree(op1); return tree; } /* This is a (real) return value -- check its type */ #ifdef DEBUG if (genActualType(op1->TypeGet()) != genActualType(info.compRetType)) { bool allowMismatch = false; // Allow TYP_BYREF to be returned as TYP_I_IMPL and vice versa if ((info.compRetType == TYP_BYREF && genActualType(op1->TypeGet()) == TYP_I_IMPL) || (op1->TypeGet() == TYP_BYREF && genActualType(info.compRetType) == TYP_I_IMPL)) allowMismatch = true; if (varTypeIsFloating(info.compRetType) && varTypeIsFloating(op1->TypeGet())) allowMismatch = true; if (!allowMismatch) NO_WAY("Return type mismatch"); } #endif } break; } return tree; } #endif /***************************************************************************** * * Transform the given tree for code generation and return an equivalent tree. */ GenTreePtr Compiler::fgMorphTree(GenTreePtr tree, MorphAddrContext* mac) { noway_assert(tree); noway_assert(tree->gtOper != GT_STMT); #ifdef DEBUG if (verbose) { if ((unsigned)JitConfig.JitBreakMorphTree() == tree->gtTreeID) { noway_assert(!"JitBreakMorphTree hit"); } } #endif #ifdef DEBUG int thisMorphNum = 0; if (verbose && treesBeforeAfterMorph) { thisMorphNum = morphNum++; printf("\nfgMorphTree (before %d):\n", thisMorphNum); gtDispTree(tree); } #endif /*------------------------------------------------------------------------- * fgMorphTree() can potentially replace a tree with another, and the * caller has to store the return value correctly. * Turn this on to always make copy of "tree" here to shake out * hidden/unupdated references. */ #ifdef DEBUG if (compStressCompile(STRESS_GENERIC_CHECK, 0)) { GenTreePtr copy; #ifdef SMALL_TREE_NODES if (GenTree::s_gtNodeSizes[tree->gtOper] == TREE_NODE_SZ_SMALL) { copy = gtNewLargeOperNode(GT_ADD, TYP_INT); } else #endif { copy = new (this, GT_CALL) GenTreeCall(TYP_INT); } copy->CopyFrom(tree, this); #if defined (LATE_DISASM) // GT_CNS_INT is considered small, so CopyFrom() won't copy all fields if ((tree->gtOper == GT_CNS_INT) && tree->IsIconHandle()) { copy->gtIntCon.gtIconHdl.gtIconHdl1 = tree->gtIntCon.gtIconHdl.gtIconHdl1; copy->gtIntCon.gtIconHdl.gtIconHdl2 = tree->gtIntCon.gtIconHdl.gtIconHdl2; } #endif DEBUG_DESTROY_NODE(tree); tree = copy; } #endif // DEBUG if (fgGlobalMorph) { /* Ensure that we haven't morphed this node already */ assert(((tree->gtFlags & GTF_MORPHED) == 0) && "ERROR: Already morphed this node!"); #if LOCAL_ASSERTION_PROP /* Before morphing the tree, we try to propagate any active assertions */ if (optLocalAssertionProp) { /* Do we have any active assertions? */ if (optAssertionCount > 0) { GenTreePtr newTree = tree; while (newTree != NULL) { tree = newTree; /* newTree is non-Null if we propagated an assertion */ newTree = optAssertionProp(apFull, tree, NULL); } noway_assert(tree != NULL); } } PREFAST_ASSUME(tree != NULL); #endif } /* Save the original un-morphed tree for fgMorphTreeDone */ GenTreePtr oldTree = tree; /* Figure out what kind of a node we have */ unsigned kind = tree->OperKind(); /* Is this a constant node? */ if (kind & GTK_CONST) { tree = fgMorphConst(tree); goto DONE; } /* Is this a leaf node? */ if (kind & GTK_LEAF) { tree = fgMorphLeaf(tree); goto DONE; } /* Is it a 'simple' unary/binary operator? */ if (kind & GTK_SMPOP) { tree = fgMorphSmpOp(tree, mac); goto DONE; } /* See what kind of a special operator we have here */ switch (tree->OperGet()) { case GT_FIELD: tree = fgMorphField(tree, mac); break; case GT_CALL: tree = fgMorphCall(tree->AsCall()); break; case GT_ARR_BOUNDS_CHECK: #ifdef FEATURE_SIMD case GT_SIMD_CHK: #endif // FEATURE_SIMD { fgSetRngChkTarget(tree); GenTreeBoundsChk* bndsChk = tree->AsBoundsChk(); bndsChk->gtArrLen = fgMorphTree(bndsChk->gtArrLen); bndsChk->gtIndex = fgMorphTree(bndsChk->gtIndex); // If the index is a comma(throw, x), just return that. if (!optValnumCSE_phase && fgIsCommaThrow(bndsChk->gtIndex)) { tree = bndsChk->gtIndex; } // Propagate effects flags upwards bndsChk->gtFlags |= (bndsChk->gtArrLen->gtFlags & GTF_ALL_EFFECT); bndsChk->gtFlags |= (bndsChk->gtIndex->gtFlags & GTF_ALL_EFFECT); // Otherwise, we don't change the tree. } break; case GT_ARR_ELEM: tree->gtArrElem.gtArrObj = fgMorphTree(tree->gtArrElem.gtArrObj); tree->gtFlags |= tree->gtArrElem.gtArrObj->gtFlags & GTF_ALL_EFFECT; unsigned dim; for (dim = 0; dim < tree->gtArrElem.gtArrRank; dim++) { tree->gtArrElem.gtArrInds[dim] = fgMorphTree(tree->gtArrElem.gtArrInds[dim]); tree->gtFlags |= tree->gtArrElem.gtArrInds[dim]->gtFlags & GTF_ALL_EFFECT; } if (fgGlobalMorph) fgSetRngChkTarget(tree, false); break; case GT_ARR_OFFSET: tree->gtArrOffs.gtOffset = fgMorphTree(tree->gtArrOffs.gtOffset); tree->gtFlags |= tree->gtArrOffs.gtOffset->gtFlags & GTF_ALL_EFFECT; tree->gtArrOffs.gtIndex = fgMorphTree(tree->gtArrOffs.gtIndex); tree->gtFlags |= tree->gtArrOffs.gtIndex->gtFlags & GTF_ALL_EFFECT; tree->gtArrOffs.gtArrObj = fgMorphTree(tree->gtArrOffs.gtArrObj); tree->gtFlags |= tree->gtArrOffs.gtArrObj->gtFlags & GTF_ALL_EFFECT; if (fgGlobalMorph) fgSetRngChkTarget(tree, false); break; case GT_CMPXCHG: tree->gtCmpXchg.gtOpLocation = fgMorphTree(tree->gtCmpXchg.gtOpLocation); tree->gtCmpXchg.gtOpValue = fgMorphTree(tree->gtCmpXchg.gtOpValue); tree->gtCmpXchg.gtOpComparand = fgMorphTree(tree->gtCmpXchg.gtOpComparand); break; default: #ifdef DEBUG gtDispTree(tree); #endif noway_assert(!"unexpected operator"); } DONE: fgMorphTreeDone(tree, oldTree DEBUG_ARG(thisMorphNum)); return tree; } #if LOCAL_ASSERTION_PROP /***************************************************************************** * * Kill all dependent assertions with regard to lclNum. * */ void Compiler::fgKillDependentAssertions(unsigned lclNum DEBUGARG(GenTreePtr tree)) { LclVarDsc * varDsc = &lvaTable[lclNum]; if (varDsc->lvPromoted) { noway_assert(varTypeIsStruct(varDsc)); // Kill the field locals. for (unsigned i = varDsc->lvFieldLclStart; i < varDsc->lvFieldLclStart + varDsc->lvFieldCnt; ++i) { fgKillDependentAssertions(i DEBUGARG(tree)); } // Fall through to kill the struct local itself. } /* All dependent assertions are killed here */ ASSERT_TP killed = BitVecOps::MakeCopy(apTraits, GetAssertionDep(lclNum)); if (killed) { AssertionIndex index = optAssertionCount; while (killed && (index > 0)) { if (BitVecOps::IsMember(apTraits, killed, index - 1)) { #ifdef DEBUG AssertionDsc* curAssertion = optGetAssertion(index); noway_assert((curAssertion->op1.lcl.lclNum == lclNum) || ((curAssertion->op2.kind == O2K_LCLVAR_COPY) && (curAssertion->op2.lcl.lclNum == lclNum))); if (verbose) { printf("\nThe assignment "); printTreeID(tree); printf(" using V%02u removes: ", curAssertion->op1.lcl.lclNum); optPrintAssertion(curAssertion); } #endif // Remove this bit from the killed mask BitVecOps::RemoveElemD(apTraits, killed, index - 1); optAssertionRemove(index); } index--; } // killed mask should now be zero noway_assert(BitVecOps::IsEmpty(apTraits, killed)); } } #endif // LOCAL_ASSERTION_PROP /***************************************************************************** * * This function is called to complete the morphing of a tree node * It should only be called once for each node. * If DEBUG is defined the flag GTF_MORPHED is checked and updated, * to enforce the invariant that each node is only morphed once. * If LOCAL_ASSERTION_PROP is enabled the result tree may be replaced * by an equivalent tree. * */ void Compiler::fgMorphTreeDone(GenTreePtr tree, GenTreePtr oldTree /* == NULL */ DEBUG_ARG(int morphNum)) { #ifdef DEBUG if (verbose && treesBeforeAfterMorph) { printf("\nfgMorphTree (after %d):\n", morphNum); gtDispTree(tree); printf(""); // in our logic this causes a flush } #endif if (!fgGlobalMorph) return; if ((oldTree != NULL) && (oldTree != tree)) { /* Ensure that we have morphed this node */ assert((tree->gtFlags & GTF_MORPHED) && "ERROR: Did not morph this node!"); #ifdef DEBUG TransferTestDataToNode(oldTree, tree); #endif } else { // Ensure that we haven't morphed this node already assert(((tree->gtFlags & GTF_MORPHED) == 0) && "ERROR: Already morphed this node!"); } if (tree->OperKind() & GTK_CONST) goto DONE; #if LOCAL_ASSERTION_PROP if (!optLocalAssertionProp) goto DONE; /* Do we have any active assertions? */ if (optAssertionCount > 0) { /* Is this an assignment to a local variable */ if ((tree->OperKind() & GTK_ASGOP) && (tree->gtOp.gtOp1->gtOper == GT_LCL_VAR || tree->gtOp.gtOp1->gtOper == GT_LCL_FLD)) { unsigned op1LclNum = tree->gtOp.gtOp1->gtLclVarCommon.gtLclNum; noway_assert(op1LclNum < lvaCount); fgKillDependentAssertions(op1LclNum DEBUGARG(tree)); } } /* If this tree makes a new assertion - make it available */ optAssertionGen(tree); #endif // LOCAL_ASSERTION_PROP DONE:; #ifdef DEBUG /* Mark this node as being morphed */ tree->gtFlags |= GTF_MORPHED; #endif } /***************************************************************************** * * Check and fold blocks of type BBJ_COND and BBJ_SWITCH on constants * Returns true if we modified the flow graph */ bool Compiler::fgFoldConditional(BasicBlock * block) { bool result = false; // We don't want to make any code unreachable if (opts.compDbgCode || opts.MinOpts()) return false; if (block->bbJumpKind == BBJ_COND) { noway_assert(block->bbTreeList && block->bbTreeList->gtPrev); GenTreePtr stmt = block->bbTreeList->gtPrev; noway_assert(stmt->gtNext == NULL); if (stmt->gtStmt.gtStmtExpr->gtOper == GT_CALL) { noway_assert(fgRemoveRestOfBlock); /* Unconditional throw - transform the basic block into a BBJ_THROW */ fgConvertBBToThrowBB(block); /* Remove 'block' from the predecessor list of 'block->bbNext' */ fgRemoveRefPred(block->bbNext, block); /* Remove 'block' from the predecessor list of 'block->bbJumpDest' */ fgRemoveRefPred(block->bbJumpDest, block); #ifdef DEBUG if (verbose) { printf("\nConditional folded at BB%02u\n", block->bbNum); printf("BB%02u becomes a BBJ_THROW\n", block->bbNum); } #endif goto DONE_COND; } noway_assert(stmt->gtStmt.gtStmtExpr->gtOper == GT_JTRUE); /* Did we fold the conditional */ noway_assert(stmt->gtStmt.gtStmtExpr->gtOp.gtOp1); GenTreePtr cond; cond = stmt->gtStmt.gtStmtExpr->gtOp.gtOp1; if (cond->OperKind() & GTK_CONST) { /* Yupee - we folded the conditional! * Remove the conditional statement */ noway_assert(cond->gtOper == GT_CNS_INT); noway_assert((block->bbNext->countOfInEdges() > 0) && (block->bbJumpDest->countOfInEdges() > 0)); /* remove the statement from bbTreelist - No need to update * the reference counts since there are no lcl vars */ fgRemoveStmt(block, stmt); // block is a BBJ_COND that we are folding the conditional for // bTaken is the path that will always be taken from block // bNotTaken is the path that will never be taken from block // BasicBlock * bTaken; BasicBlock * bNotTaken; if (cond->gtIntCon.gtIconVal != 0) { /* JTRUE 1 - transform the basic block into a BBJ_ALWAYS */ block->bbJumpKind = BBJ_ALWAYS; bTaken = block->bbJumpDest; bNotTaken = block->bbNext; } else { /* Unmark the loop if we are removing a backwards branch */ /* dest block must also be marked as a loop head and */ /* We must be able to reach the backedge block */ if ((block->bbJumpDest->isLoopHead()) && (block->bbJumpDest->bbNum <= block->bbNum) && fgReachable(block->bbJumpDest, block)) { optUnmarkLoopBlocks(block->bbJumpDest, block); } /* JTRUE 0 - transform the basic block into a BBJ_NONE */ block->bbJumpKind = BBJ_NONE; noway_assert(!(block->bbFlags & BBF_NEEDS_GCPOLL)); bTaken = block->bbNext; bNotTaken = block->bbJumpDest; } if (fgHaveValidEdgeWeights) { // We are removing an edge from block to bNotTaken // and we have already computed the edge weights, so // we will try to adjust some of the weights // flowList * edgeTaken = fgGetPredForBlock(bTaken, block); BasicBlock * bUpdated = NULL; // non-NULL if we updated the weight of an internal block // We examine the taken edge (block -> bTaken) // if block has valid profile weight and bTaken does not we try to adjust bTaken's weight // else if bTaken has valid profile weight and block does not we try to adjust block's weight // We can only adjust the block weights when (the edge block -> bTaken) is the only edge into bTaken // if (block->bbFlags & BBF_PROF_WEIGHT) { // The edge weights for (block -> bTaken) are 100% of block's weight edgeTaken->flEdgeWeightMin = block->bbWeight; edgeTaken->flEdgeWeightMax = block->bbWeight; if ((bTaken->bbFlags & BBF_PROF_WEIGHT) == 0) { if ((bTaken->countOfInEdges() == 1) || (bTaken->bbWeight < block->bbWeight)) { // Update the weight of bTaken bTaken->inheritWeight(block); bUpdated = bTaken; } } } else if (bTaken->bbFlags & BBF_PROF_WEIGHT) { if (bTaken->countOfInEdges() == 1) { // There is only one in edge to bTaken edgeTaken->flEdgeWeightMin = bTaken->bbWeight; edgeTaken->flEdgeWeightMax = bTaken->bbWeight; // Update the weight of block block->inheritWeight(bTaken); bUpdated = block; } } if (bUpdated != NULL) { flowList * edge; // Now fix the weights of the edges out of 'bUpdated' switch (bUpdated->bbJumpKind) { case BBJ_NONE: edge = fgGetPredForBlock(bUpdated->bbNext, bUpdated); edge->flEdgeWeightMax = bUpdated->bbWeight; break; case BBJ_COND: edge = fgGetPredForBlock(bUpdated->bbNext, bUpdated); edge->flEdgeWeightMax = bUpdated->bbWeight; __fallthrough; case BBJ_ALWAYS: edge = fgGetPredForBlock(bUpdated->bbJumpDest, bUpdated); edge->flEdgeWeightMax = bUpdated->bbWeight; break; default: // We don't handle BBJ_SWITCH break; } } } /* modify the flow graph */ /* Remove 'block' from the predecessor list of 'bNotTaken' */ fgRemoveRefPred(bNotTaken, block); #ifdef DEBUG if (verbose) { printf("\nConditional folded at BB%02u\n", block->bbNum); printf("BB%02u becomes a %s", block->bbNum, block->bbJumpKind == BBJ_ALWAYS ? "BBJ_ALWAYS" : "BBJ_NONE"); if (block->bbJumpKind == BBJ_ALWAYS) printf(" to BB%02u", block->bbJumpDest->bbNum); printf("\n"); } #endif /* if the block was a loop condition we may have to modify * the loop table */ for (unsigned loopNum = 0; loopNum < optLoopCount; loopNum++) { /* Some loops may have been already removed by * loop unrolling or conditional folding */ if (optLoopTable[loopNum].lpFlags & LPFLG_REMOVED) continue; /* We are only interested in the loop bottom */ if (optLoopTable[loopNum].lpBottom == block) { if (cond->gtIntCon.gtIconVal == 0) { /* This was a bogus loop (condition always false) * Remove the loop from the table */ optLoopTable[loopNum].lpFlags |= LPFLG_REMOVED; #ifdef DEBUG if (verbose) { printf("Removing loop L%02u (from BB%02u to BB%02u)\n\n", loopNum, optLoopTable[loopNum].lpFirst ->bbNum, optLoopTable[loopNum].lpBottom->bbNum); } #endif } } } DONE_COND: result = true; } } else if (block->bbJumpKind == BBJ_SWITCH) { noway_assert(block->bbTreeList && block->bbTreeList->gtPrev); GenTreePtr stmt = block->bbTreeList->gtPrev; noway_assert(stmt->gtNext == NULL); if (stmt->gtStmt.gtStmtExpr->gtOper == GT_CALL) { noway_assert(fgRemoveRestOfBlock); /* Unconditional throw - transform the basic block into a BBJ_THROW */ fgConvertBBToThrowBB(block); /* update the flow graph */ unsigned jumpCnt = block->bbJumpSwt->bbsCount; BasicBlock * * jumpTab = block->bbJumpSwt->bbsDstTab; for (unsigned val = 0; val < jumpCnt; val++, jumpTab++) { BasicBlock * curJump = *jumpTab; /* Remove 'block' from the predecessor list of 'curJump' */ fgRemoveRefPred(curJump, block); } #ifdef DEBUG if (verbose) { printf("\nConditional folded at BB%02u\n", block->bbNum); printf("BB%02u becomes a BBJ_THROW\n", block->bbNum); } #endif goto DONE_SWITCH; } noway_assert(stmt->gtStmt.gtStmtExpr->gtOper == GT_SWITCH); /* Did we fold the conditional */ noway_assert(stmt->gtStmt.gtStmtExpr->gtOp.gtOp1); GenTreePtr cond; cond = stmt->gtStmt.gtStmtExpr->gtOp.gtOp1; if (cond->OperKind() & GTK_CONST) { /* Yupee - we folded the conditional! * Remove the conditional statement */ noway_assert(cond->gtOper == GT_CNS_INT); /* remove the statement from bbTreelist - No need to update * the reference counts since there are no lcl vars */ fgRemoveStmt(block, stmt); /* modify the flow graph */ /* Find the actual jump target */ unsigned switchVal; switchVal = (unsigned)cond->gtIntCon.gtIconVal; unsigned jumpCnt; jumpCnt = block->bbJumpSwt->bbsCount; BasicBlock * * jumpTab; jumpTab = block->bbJumpSwt->bbsDstTab; bool foundVal; foundVal = false; for (unsigned val = 0; val < jumpCnt; val++, jumpTab++) { BasicBlock * curJump = *jumpTab; assert (curJump->countOfInEdges() > 0); // If val matches switchVal or we are at the last entry and // we never found the switch value then set the new jump dest if ( (val == switchVal) || (!foundVal && (val == jumpCnt-1))) { if (curJump != block->bbNext) { /* transform the basic block into a BBJ_ALWAYS */ block->bbJumpKind = BBJ_ALWAYS; block->bbJumpDest = curJump; //if we are jumping backwards, make sure we have a GC Poll. if (curJump->bbNum > block->bbNum) block->bbFlags &= ~BBF_NEEDS_GCPOLL; } else { /* transform the basic block into a BBJ_NONE */ block->bbJumpKind = BBJ_NONE; block->bbFlags &= ~BBF_NEEDS_GCPOLL; } foundVal = true; } else { /* Remove 'block' from the predecessor list of 'curJump' */ fgRemoveRefPred(curJump, block); } } #ifdef DEBUG if (verbose) { printf("\nConditional folded at BB%02u\n", block->bbNum); printf("BB%02u becomes a %s", block->bbNum, block->bbJumpKind == BBJ_ALWAYS ? "BBJ_ALWAYS" : "BBJ_NONE"); if (block->bbJumpKind == BBJ_ALWAYS) printf(" to BB%02u", block->bbJumpDest->bbNum); printf("\n"); } #endif DONE_SWITCH: result = true; } } return result; } //***************************************************************************** // // Morphs a single statement in a block. // Can be called anytime, unlike fgMorphStmts() which should only be called once. // // Returns true if 'stmt' was removed from the block. // Returns false if 'stmt' is still in the block (even if other statements were removed). // bool Compiler::fgMorphBlockStmt(BasicBlock * block, GenTreePtr stmt DEBUGARG(const char * msg) ) { noway_assert(stmt->gtOper == GT_STMT); compCurBB = block; compCurStmt = stmt; GenTreePtr morph = fgMorphTree(stmt->gtStmt.gtStmtExpr); // Bug 1106830 - During the CSE phase we can't just remove // morph->gtOp.gtOp2 as it could contain CSE expressions. // This leads to a noway_assert in OptCSE.cpp when // searching for the removed CSE ref. (using gtFindLink) // if (!optValnumCSE_phase) { /* Check for morph as a GT_COMMA with an unconditional throw */ if (fgIsCommaThrow(morph, true)) { #ifdef DEBUG if (verbose) { printf("Folding a top-level fgIsCommaThrow stmt\n"); printf("Removing op2 as unreachable:\n"); gtDispTree(morph->gtOp.gtOp2); printf("\n"); } #endif /* Use the call as the new stmt */ morph = morph->gtOp.gtOp1; noway_assert(morph->gtOper == GT_CALL); } /* we can get a throw as a statement root*/ if (fgIsThrow(morph)) { #ifdef DEBUG if (verbose) { printf("We have a top-level fgIsThrow stmt\n"); printf("Removing the rest of block as unreachable:\n"); } #endif noway_assert((morph->gtFlags & GTF_COLON_COND) == 0); fgRemoveRestOfBlock = true; } } stmt->gtStmt.gtStmtExpr = morph; /* Can the entire tree be removed ? */ bool removedStmt = fgCheckRemoveStmt(block, stmt); /* Or this is the last statement of a conditional branch that was just folded */ if ((!removedStmt) && (stmt->gtNext == NULL) && !fgRemoveRestOfBlock) { if (fgFoldConditional(block)) { if (block->bbJumpKind != BBJ_THROW) removedStmt = true; } } if (!removedStmt) { /* Have to re-do the evaluation order since for example * some later code does not expect constants as op1 */ gtSetStmtInfo(stmt); /* Have to re-link the nodes for this statement */ fgSetStmtSeq(stmt); } #ifdef DEBUG if (verbose) { printf("%s %s tree:\n", msg, (removedStmt ? "removed" : "morphed")); gtDispTree(morph); printf("\n"); } #endif if (fgRemoveRestOfBlock) { /* Remove the rest of the stmts in the block */ while (stmt->gtNext) { stmt = stmt->gtNext; noway_assert(stmt->gtOper == GT_STMT); fgRemoveStmt(block, stmt); } // The rest of block has been removed // and we will always throw an exception // Update succesors of block fgRemoveBlockAsPred(block); // For compDbgCode, we prepend an empty BB as the firstBB, it is BBJ_NONE. // We should not convert it to a ThrowBB. if ((block != fgFirstBB) || ((fgFirstBB->bbFlags & BBF_INTERNAL) == 0) ) { // Convert block to a throw bb fgConvertBBToThrowBB(block); } #ifdef DEBUG if (verbose) { printf("\n%s Block BB%02u becomes a throw block.\n", msg, block->bbNum); } #endif fgRemoveRestOfBlock = false; } return removedStmt; } /***************************************************************************** * * Morph the statements of the given block. * This function should be called just once for a block. Use fgMorphBlockStmt() * for reentrant calls. */ void Compiler::fgMorphStmts(BasicBlock * block, bool * mult, bool * lnot, bool * loadw) { fgRemoveRestOfBlock = false; noway_assert(fgExpandInline == false); /* Make the current basic block address available globally */ compCurBB = block; *mult = *lnot = *loadw = false; fgCurrentlyInUseArgTemps = hashBv::Create(this); GenTreePtr stmt, prev; for (stmt = block->bbTreeList, prev = NULL; stmt; prev = stmt->gtStmt.gtStmtExpr, stmt = stmt->gtNext) { noway_assert(stmt->gtOper == GT_STMT); if (fgRemoveRestOfBlock) { fgRemoveStmt(block, stmt); continue; } #ifdef FEATURE_SIMD if (!opts.MinOpts() && stmt->gtStmt.gtStmtExpr->TypeGet() == TYP_FLOAT && stmt->gtStmt.gtStmtExpr->OperGet() == GT_ASG) { fgMorphCombineSIMDFieldAssignments(block, stmt); } #endif fgMorphStmt = stmt; compCurStmt = stmt; GenTreePtr tree = stmt->gtStmt.gtStmtExpr; #ifdef DEBUG compCurStmtNum++; if (stmt == block->bbTreeList) block->bbStmtNum = compCurStmtNum; // Set the block->bbStmtNum unsigned oldHash = verbose ? gtHashValue(tree) : DUMMY_INIT(~0); if (verbose) { printf("\nfgMorphTree BB%02u, stmt %d (before)\n", block->bbNum, compCurStmtNum); gtDispTree(tree); } #endif /* Morph this statement tree */ GenTreePtr morph = fgMorphTree(tree); // mark any outgoing arg temps as free so we can reuse them in the next statement. fgCurrentlyInUseArgTemps->ZeroAll(); // Has fgMorphStmt been sneakily changed ? if (stmt->gtStmt.gtStmtExpr != tree) { /* This must be tailcall. Ignore 'morph' and carry on with the tail-call node */ morph = stmt->gtStmt.gtStmtExpr; noway_assert(compTailCallUsed); noway_assert((morph->gtOper == GT_CALL) && morph->AsCall()->IsTailCall()); noway_assert(stmt->gtNext == NULL); GenTreeCall* call = morph->AsCall(); // Could either be // - a tail call dispatched via helper in which case block will be ending with BBJ_THROW or // - a fast call made as jmp in which case block will be ending with BBJ_RETURN and marked as containing a jmp. noway_assert((call->IsTailCallViaHelper() && (compCurBB->bbJumpKind == BBJ_THROW)) || (call->IsFastTailCall() && (compCurBB->bbJumpKind == BBJ_RETURN) && (compCurBB->bbFlags & BBF_HAS_JMP))); } else if (block != compCurBB) { /* This must be a tail call that caused a GCPoll to get injected. We haven't actually morphed the call yet but the flag still got set, clear it here... */ #ifdef DEBUG tree->gtFlags &= ~GTF_MORPHED; #endif noway_assert(compTailCallUsed); noway_assert((tree->gtOper == GT_CALL) && tree->AsCall()->IsTailCall()); noway_assert(stmt->gtNext == NULL); GenTreeCall* call = morph->AsCall(); // Could either be // - a tail call dispatched via helper in which case block will be ending with BBJ_THROW or // - a fast call made as jmp in which case block will be ending with BBJ_RETURN and marked as containing a jmp. noway_assert((call->IsTailCallViaHelper() && (compCurBB->bbJumpKind == BBJ_THROW)) || (call->IsFastTailCall() && (compCurBB->bbJumpKind == BBJ_RETURN) && (compCurBB->bbFlags & BBF_HAS_JMP))); } #ifdef DEBUG if (compStressCompile(STRESS_CLONE_EXPR, 30)) { // Clone all the trees to stress gtCloneExpr() if (verbose) { printf("\nfgMorphTree (stressClone from):\n"); gtDispTree(morph); } morph = gtCloneExpr(morph); noway_assert(morph); if (verbose) { printf("\nfgMorphTree (stressClone to):\n"); gtDispTree(morph); } } /* If the hash value changes. we modified the tree during morphing */ if (verbose) { unsigned newHash = gtHashValue(morph); if (newHash != oldHash) { printf("\nfgMorphTree BB%02u, stmt %d (after)\n", block->bbNum, compCurStmtNum); gtDispTree(morph); } } #endif /* Check for morph as a GT_COMMA with an unconditional throw */ if (!gtIsActiveCSE_Candidate(morph) && fgIsCommaThrow(morph, true)) { /* Use the call as the new stmt */ morph = morph->gtOp.gtOp1; noway_assert(morph->gtOper == GT_CALL); noway_assert((morph->gtFlags & GTF_COLON_COND) == 0); fgRemoveRestOfBlock = true; } stmt->gtStmt.gtStmtExpr = tree = morph; noway_assert(fgPtrArgCntCur == 0); if (fgRemoveRestOfBlock) continue; /* Has the statement been optimized away */ if (fgCheckRemoveStmt(block, stmt)) continue; /* Check if this block ends with a conditional branch that can be folded */ if (fgFoldConditional(block)) continue; if (block->hasTryIndex()) continue; #if OPT_MULT_ADDSUB /* Note whether we have two or more +=/-= operators in a row */ if (tree->gtOper == GT_ASG_ADD || tree->gtOper == GT_ASG_SUB) { if (prev && prev->gtOper == tree->gtOper) *mult = true; } #endif /* Note "x = a[i] & icon" followed by "x |= a[i] << 8" */ if (tree->gtOper == GT_ASG_OR && prev && prev->gtOper == GT_ASG) { *loadw = true; } } if (fgRemoveRestOfBlock) { if ((block->bbJumpKind == BBJ_COND) || (block->bbJumpKind == BBJ_SWITCH)) { GenTreePtr first = block->bbTreeList; noway_assert(first); GenTreePtr last = first->gtPrev; noway_assert(last && last->gtNext == NULL); GenTreePtr lastStmt = last->gtStmt.gtStmtExpr; if (((block->bbJumpKind == BBJ_COND ) && (lastStmt->gtOper == GT_JTRUE )) || ((block->bbJumpKind == BBJ_SWITCH) && (lastStmt->gtOper == GT_SWITCH)) ) { GenTreePtr op1 = lastStmt->gtOp.gtOp1; if (op1->OperKind() & GTK_RELOP) { /* Unmark the comparison node with GTF_RELOP_JMP_USED */ op1->gtFlags &= ~GTF_RELOP_JMP_USED; } last->gtStmt.gtStmtExpr = fgMorphTree(op1); } } /* Mark block as a BBJ_THROW block */ fgConvertBBToThrowBB(block); } noway_assert(fgExpandInline == false); #if FEATURE_FASTTAILCALL GenTreePtr recursiveTailCall = nullptr; if (block->endsWithTailCallConvertibleToLoop(this, &recursiveTailCall)) { fgMorphRecursiveFastTailCallIntoLoop(block, recursiveTailCall->AsCall()); } #endif #ifdef DEBUG compCurBB = (BasicBlock*)INVALID_POINTER_VALUE; #endif // Reset this back so that it doesn't leak out impacting other blocks fgRemoveRestOfBlock = false; } /***************************************************************************** * * Morph the blocks of the method. * Returns true if the basic block list is modified. * This function should be called just once. */ void Compiler::fgMorphBlocks() { #ifdef DEBUG if (verbose) printf("\n*************** In fgMorphBlocks()\n"); #endif /* Since fgMorphTree can be called after various optimizations to re-arrange * the nodes we need a global flag to signal if we are during the one-pass * global morphing */ fgGlobalMorph = true; #if LOCAL_ASSERTION_PROP // // Local assertion prop is enabled if we are optimized // optLocalAssertionProp = (!opts.compDbgCode && !opts.MinOpts()); if (optLocalAssertionProp) { // // Initialize for local assertion prop // optAssertionInit(true); } #elif ASSERTION_PROP // // If LOCAL_ASSERTION_PROP is not set // and we have global assertion prop // then local assertion prop is always off // optLocalAssertionProp = false; #endif /*------------------------------------------------------------------------- * Process all basic blocks in the function */ BasicBlock * block = fgFirstBB; noway_assert(block); #ifdef DEBUG compCurStmtNum = 0; #endif do { #if OPT_MULT_ADDSUB bool mult = false; #endif #if OPT_BOOL_OPS bool lnot = false; #endif bool loadw = false; #ifdef DEBUG if (verbose) printf("\nMorphing BB%02u of '%s'\n", block->bbNum, info.compFullName); #endif #if LOCAL_ASSERTION_PROP if (optLocalAssertionProp) { // // Clear out any currently recorded assertion candidates // before processing each basic block, // also we must handle QMARK-COLON specially // optAssertionReset(0); } #endif /* Process all statement trees in the basic block */ GenTreePtr tree; fgMorphStmts(block, &mult, &lnot, &loadw); #if OPT_MULT_ADDSUB if (mult && (opts.compFlags & CLFLG_TREETRANS) && !opts.compDbgCode && !opts.MinOpts()) { for (tree = block->bbTreeList; tree; tree = tree->gtNext) { noway_assert(tree->gtOper == GT_STMT); GenTreePtr last = tree->gtStmt.gtStmtExpr; if (last->gtOper == GT_ASG_ADD || last->gtOper == GT_ASG_SUB) { GenTreePtr temp; GenTreePtr next; GenTreePtr dst1 = last->gtOp.gtOp1; GenTreePtr src1 = last->gtOp.gtOp2; if (!last->IsCnsIntOrI()) goto NOT_CAFFE; if (dst1->gtOper != GT_LCL_VAR) goto NOT_CAFFE; if (!src1->IsCnsIntOrI()) goto NOT_CAFFE; for (;;) { GenTreePtr dst2; GenTreePtr src2; /* Look at the next statement */ temp = tree->gtNext; if (!temp) goto NOT_CAFFE; noway_assert(temp->gtOper == GT_STMT); next = temp->gtStmt.gtStmtExpr; if (next->gtOper != last->gtOper) goto NOT_CAFFE; if (next->gtType != last->gtType) goto NOT_CAFFE; dst2 = next->gtOp.gtOp1; src2 = next->gtOp.gtOp2; if (dst2->gtOper != GT_LCL_VAR) goto NOT_CAFFE; if (dst2->gtLclVarCommon.gtLclNum != dst1->gtLclVarCommon.gtLclNum) goto NOT_CAFFE; if (!src2->IsCnsIntOrI()) goto NOT_CAFFE; if (last->gtOverflow() != next->gtOverflow()) goto NOT_CAFFE; const ssize_t i1 = src1->gtIntCon.gtIconVal; const ssize_t i2 = src2->gtIntCon.gtIconVal; const ssize_t itemp = i1 + i2; /* if the operators are checking for overflow, check for overflow of the operands */ if (next->gtOverflow()) { if (next->TypeGet() == TYP_LONG) { if (next->gtFlags & GTF_UNSIGNED) { ClrSafeInt<UINT64> si1(i1); if ((si1 + ClrSafeInt<UINT64>(i2)).IsOverflow()) goto NOT_CAFFE; } else { ClrSafeInt<INT64> si1(i1); if ((si1 + ClrSafeInt<INT64>(i2)).IsOverflow()) goto NOT_CAFFE; } } else if (next->gtFlags & GTF_UNSIGNED) { ClrSafeInt<UINT32> si1(i1); if ((si1 + ClrSafeInt<UINT32>(i2)).IsOverflow()) goto NOT_CAFFE; } else { ClrSafeInt<INT32> si1(i1); if ((si1 + ClrSafeInt<INT32>(i2)).IsOverflow()) goto NOT_CAFFE; } } /* Fold the two increments/decrements into one */ src1->gtIntCon.gtIconVal = itemp; #ifdef _TARGET_64BIT_ if (src1->gtType == TYP_INT) { src1->AsIntCon()->TruncateOrSignExtend32(); } #endif //_TARGET_64BIT_ /* Remove the second statement completely */ noway_assert(tree->gtNext == temp); noway_assert(temp->gtPrev == tree); if (temp->gtNext) { noway_assert(temp->gtNext->gtPrev == temp); temp->gtNext->gtPrev = tree; tree->gtNext = temp->gtNext; } else { tree->gtNext = 0; noway_assert(block->bbTreeList->gtPrev == temp); block->bbTreeList->gtPrev = tree; } } } NOT_CAFFE:; } } #endif /* Are we using a single return block? */ if (block->bbJumpKind == BBJ_RETURN) { if ((genReturnBB != nullptr) && (genReturnBB != block) && ((block->bbFlags & BBF_HAS_JMP) == 0)) { /* We'll jump to the genReturnBB */ #if !defined(_TARGET_X86_) if (info.compFlags & CORINFO_FLG_SYNCH) { fgConvertSyncReturnToLeave(block); } else #endif // !_TARGET_X86_ { block->bbJumpKind = BBJ_ALWAYS; block->bbJumpDest = genReturnBB; fgReturnCount--; } // Note 1: A block is not guaranteed to have a last stmt if its jump kind is BBJ_RETURN. // For example a method returning void could have an empty block with jump kind BBJ_RETURN. // Such blocks do materialize as part of in-lining. // // Note 2: A block with jump kind BBJ_RETURN does not necessarily need to end with GT_RETURN. // It could end with a tail call or rejected tail call or monitor.exit or a GT_INTRINSIC. // For now it is safe to explicitly check whether last stmt is GT_RETURN if genReturnLocal // is BAD_VAR_NUM. // // TODO: Need to characterize the last top level stmt of a block ending with BBJ_RETURN. GenTreePtr last = (block->bbTreeList != nullptr) ? block->bbTreeList->gtPrev : nullptr; GenTreePtr ret = (last != nullptr) ? last->gtStmt.gtStmtExpr : nullptr; //replace the GT_RETURN node to be a GT_ASG that stores the return value into genReturnLocal. if (genReturnLocal != BAD_VAR_NUM) { // Method must be returning a value other than TYP_VOID. noway_assert(compMethodHasRetVal()); // This block must be ending with a GT_RETURN noway_assert(last != nullptr); noway_assert(last->gtOper == GT_STMT); noway_assert(last->gtNext == nullptr); noway_assert(ret != nullptr); // GT_RETURN must have non-null operand as the method is returning the value assigned to genReturnLocal noway_assert(ret->OperGet() == GT_RETURN); noway_assert(ret->gtGetOp1() != nullptr); noway_assert(ret->gtGetOp2() == nullptr); last->gtStmt.gtStmtExpr = gtNewTempAssign(genReturnLocal, ret->gtGetOp1()); //make sure that copy-prop ignores this assignment. last->gtStmt.gtStmtExpr->gtFlags |= GTF_DONT_CSE; } else if (ret != nullptr && ret->OperGet() == GT_RETURN) { // This block ends with a GT_RETURN noway_assert(last != nullptr); noway_assert(last->gtOper == GT_STMT); noway_assert(last->gtNext == nullptr); // Must be a void GT_RETURN with null operand; delete it as this block branches to oneReturn block noway_assert(ret->TypeGet() == TYP_VOID); noway_assert(ret->gtGetOp1() == nullptr); noway_assert(ret->gtGetOp2() == nullptr); fgRemoveStmt(block, last); } #ifdef DEBUG if (verbose) { printf("morph BB%02u to point at onereturn. New block is\n", block->bbNum); fgTableDispBasicBlock(block); } #endif } } block = block->bbNext; } while (block); /* We are done with the global morphing phase */ fgGlobalMorph = false; #ifdef DEBUG if (verboseTrees) fgDispBasicBlocks(true); #endif } /***************************************************************************** * * Make some decisions about the kind of code to generate. */ void Compiler::fgSetOptions() { /* Should we force fully interruptible code ? */ #ifdef DEBUG if (JitConfig.JitFullyInt() || compStressCompile(STRESS_GENERIC_VARN, 30)) { noway_assert(!codeGen->isGCTypeFixed()); genInterruptible = true; } #endif #ifdef DEBUGGING_SUPPORT if (opts.compDbgCode) { assert(!codeGen->isGCTypeFixed()); genInterruptible = true; // debugging is easier this way ... } #endif /* Assume we won't need an explicit stack frame if this is allowed */ // CORINFO_HELP_TAILCALL won't work with localloc because of the restoring of // the callee-saved registers. noway_assert(!compTailCallUsed || !compLocallocUsed); if (compLocallocUsed) codeGen->setFramePointerRequired(true); #ifdef _TARGET_X86_ if (compTailCallUsed) codeGen->setFramePointerRequired(true); #endif // _TARGET_X86_ if (!opts.genFPopt) codeGen->setFramePointerRequired(true); // Assert that the EH table has been initialized by now. Note that // compHndBBtabAllocCount never decreases; it is a high-water mark // of table allocation. In contrast, compHndBBtabCount does shrink // if we delete a dead EH region, and if it shrinks to zero, the // table pointer compHndBBtab is unreliable. assert(compHndBBtabAllocCount >= info.compXcptnsCount); #ifdef _TARGET_X86_ // Note: this case, and the !X86 case below, should both use the // !X86 path. This would require a few more changes for X86 to use // compHndBBtabCount (the current number of EH clauses) instead of // info.compXcptnsCount (the number of EH clauses in IL), such as // in ehNeedsShadowSPslots(). This is because sometimes the IL has // an EH clause that we delete as statically dead code before we // get here, leaving no EH clauses left, and thus no requirement // to use a frame pointer because of EH. But until all the code uses // the same test, leave info.compXcptnsCount here. if (info.compXcptnsCount > 0) codeGen->setFramePointerRequiredEH(true); #else // !_TARGET_X86_ if (compHndBBtabCount > 0) codeGen->setFramePointerRequiredEH(true); #endif // _TARGET_X86_ // fpPtrArgCntMax records the maximum number of pushed arguments // Depending upon this value of the maximum number of pushed arguments // we may need to use an EBP frame or be partially interuptible // if (!compCanEncodePtrArgCntMax()) { #ifdef DEBUG if (verbose) printf("Too many pushed arguments for fully interruptible encoding, marking method as partially interruptible\n"); #endif genInterruptible = false; } if (fgPtrArgCntMax >= sizeof(unsigned)) { #ifdef DEBUG if (verbose) printf("Too many pushed arguments for an ESP based encoding, forcing an EBP frame\n"); #endif codeGen->setFramePointerRequiredGCInfo(true); } #if INLINE_NDIRECT if (info.compCallUnmanaged) { codeGen->setFramePointerRequired(true); // Setup of Pinvoke frame currently requires an EBP style frame } #endif if (info.compPublishStubParam) { codeGen->setFramePointerRequiredGCInfo(true); } if (opts.compNeedSecurityCheck) { codeGen->setFramePointerRequiredGCInfo(true); #ifndef JIT32_GCENCODER // The decoder only reports objects in frames with exceptions if the frame // is fully interruptible. // Even if there is no catch or other way to resume execution in this frame // the VM requires the security object to remain alive until later, so // Frames with security objects must be fully interruptible. genInterruptible = true; #endif // JIT32_GCENCODER } if (compIsProfilerHookNeeded()) { codeGen->setFramePointerRequired(true); } if (info.compIsVarArgs) { // Code that initializes lvaVarargsBaseOfStkArgs requires this to be EBP relative. codeGen->setFramePointerRequiredGCInfo(true); } if (lvaReportParamTypeArg()) { codeGen->setFramePointerRequiredGCInfo(true); } // printf("method will %s be fully interruptible\n", genInterruptible ? " " : "not"); } /*****************************************************************************/ GenTreePtr Compiler::fgInitThisClass() { noway_assert(!compIsForInlining()); CORINFO_LOOKUP_KIND kind = info.compCompHnd->getLocationOfThisType(info.compMethodHnd); if (!kind.needsRuntimeLookup) { return fgGetSharedCCtor(info.compClassHnd); } else { // Collectible types requires that for shared generic code, if we use the generic context paramter // that we report it. (This is a conservative approach, we could detect some cases particularly when the // context parameter is this that we don't need the eager reporting logic.) lvaGenericsContextUsed = true; switch (kind.runtimeLookupKind) { case CORINFO_LOOKUP_THISOBJ : // This code takes a this pointer; but we need to pass the static method desc to get the right point in the hierarchy { GenTreePtr vtTree = gtNewLclvNode(info.compThisArg, TYP_REF); // Vtable pointer of this object vtTree = gtNewOperNode(GT_IND, TYP_I_IMPL, vtTree); vtTree->gtFlags |= GTF_EXCEPT; // Null-pointer exception GenTreePtr methodHnd = gtNewIconEmbMethHndNode(info.compMethodHnd); return gtNewHelperCallNode(CORINFO_HELP_INITINSTCLASS, TYP_VOID, 0, gtNewArgList(vtTree, methodHnd)); } case CORINFO_LOOKUP_CLASSPARAM : { GenTreePtr vtTree = gtNewLclvNode(info.compTypeCtxtArg, TYP_I_IMPL); return gtNewHelperCallNode(CORINFO_HELP_INITCLASS, TYP_VOID, 0, gtNewArgList(vtTree)); } case CORINFO_LOOKUP_METHODPARAM : { GenTreePtr methHndTree = gtNewLclvNode(info.compTypeCtxtArg, TYP_I_IMPL); return gtNewHelperCallNode(CORINFO_HELP_INITINSTCLASS, TYP_VOID, 0, gtNewArgList(gtNewIconNode(0),methHndTree)); } } } noway_assert(!"Unknown LOOKUP_KIND"); UNREACHABLE(); } #ifdef DEBUG /***************************************************************************** * * Tree walk callback to make sure no GT_QMARK nodes are present in the tree, * except for the allowed ? 1 : 0; pattern. */ Compiler::fgWalkResult Compiler::fgAssertNoQmark(GenTreePtr* tree, fgWalkData* data) { if ((*tree)->OperGet() == GT_QMARK) { fgCheckQmarkAllowedForm(*tree); } return WALK_CONTINUE; } void Compiler::fgCheckQmarkAllowedForm(GenTree* tree) { assert(tree->OperGet() == GT_QMARK); #ifndef LEGACY_BACKEND assert(!"Qmarks beyond morph disallowed."); #else // LEGACY_BACKEND GenTreePtr colon = tree->gtOp.gtOp2; assert(colon->gtOp.gtOp1->gtOper == GT_CNS_INT); assert(colon->gtOp.gtOp1->AsIntCon()->IconValue() == 0); assert(colon->gtOp.gtOp2->gtOper == GT_CNS_INT); assert(colon->gtOp.gtOp2->AsIntCon()->IconValue() == 1); #endif // LEGACY_BACKEND } /***************************************************************************** * * Verify that the importer has created GT_QMARK nodes in a way we can * process them. The following is allowed: * * 1. A top level qmark. Top level qmark is of the form: * a) (bool) ? (void) : (void) OR * b) V0N = (bool) ? (type) : (type) * * 2. Recursion is allowed at the top level, i.e., a GT_QMARK can be a child * of either op1 of colon or op2 of colon but not a child of any other * operator. */ void Compiler::fgPreExpandQmarkChecks(GenTreePtr expr) { GenTreePtr topQmark = fgGetTopLevelQmark(expr); // If the top level Qmark is null, then scan the tree to make sure // there are no qmarks within it. if (topQmark == NULL) { fgWalkTreePre(&expr, Compiler::fgAssertNoQmark, NULL); } else { // We could probably expand the cond node also, but don't think the extra effort is necessary, // so let's just assert the cond node of a top level qmark doesn't have further top level qmarks. fgWalkTreePre(&topQmark->gtOp.gtOp1, Compiler::fgAssertNoQmark, NULL); fgPreExpandQmarkChecks(topQmark->gtOp.gtOp2->gtOp.gtOp1); fgPreExpandQmarkChecks(topQmark->gtOp.gtOp2->gtOp.gtOp2); } } #endif // DEBUG /***************************************************************************** * * Get the top level GT_QMARK node in a given "expr", return NULL if such a * node is not present. If the top level GT_QMARK node is assigned to a * GT_LCL_VAR, then return the lcl node in ppDst. * */ GenTreePtr Compiler::fgGetTopLevelQmark(GenTreePtr expr, GenTreePtr* ppDst /* = NULL */) { if (ppDst != NULL) { *ppDst = NULL; } GenTreePtr topQmark = NULL; if (expr->gtOper == GT_QMARK) { topQmark = expr; } else if (expr->gtOper == GT_ASG && expr->gtOp.gtOp2->gtOper == GT_QMARK && expr->gtOp.gtOp1->gtOper == GT_LCL_VAR) { topQmark = expr->gtOp.gtOp2; if (ppDst != NULL) { *ppDst = expr->gtOp.gtOp1; } } return topQmark; } /********************************************************************************* * * For a castclass helper call, * Importer creates the following tree: * tmp = (op1 == null) ? op1 : ((*op1 == (cse = op2, cse)) ? op1 : helper()); * * This method splits the qmark expression created by the importer into the * following blocks: (block, asg, cond1, cond2, helper, remainder) * Notice that op1 is the result for both the conditions. So we coalesce these * assignments into a single block instead of two blocks resulting a nested diamond. * * +---------->-----------+ * | | | * ^ ^ v * | | | * block-->asg-->cond1--+-->cond2--+-->helper--+-->remainder * * We expect to achieve the following codegen: * mov rsi, rdx tmp = op1 // asgBlock * test rsi, rsi goto skip if tmp == null ? // cond1Block * je SKIP * mov rcx, 0x76543210 cns = op2 // cond2Block * cmp qword ptr [rsi], rcx goto skip if *tmp == op2 * je SKIP * call CORINFO_HELP_CHKCASTCLASS_SPECIAL tmp = helper(cns, tmp) // helperBlock * mov rsi, rax * SKIP: // remainderBlock * tmp has the result. * */ void Compiler::fgExpandQmarkForCastInstOf(BasicBlock* block, GenTreePtr stmt) { #ifdef DEBUG if (verbose) { printf("\nExpanding CastInstOf qmark in BB%02u (before)\n", block->bbNum); fgDispBasicBlocks(block, block, true); } #endif // DEBUG GenTreePtr expr = stmt->gtStmt.gtStmtExpr; GenTreePtr dst = nullptr; GenTreePtr qmark = fgGetTopLevelQmark(expr, &dst); noway_assert(dst != nullptr); assert(qmark->gtFlags & GTF_QMARK_CAST_INSTOF); // Get cond, true, false exprs for the qmark. GenTreePtr condExpr = qmark->gtGetOp1(); GenTreePtr trueExpr = qmark->gtGetOp2()->AsColon()->ThenNode(); GenTreePtr falseExpr = qmark->gtGetOp2()->AsColon()->ElseNode(); // Get cond, true, false exprs for the nested qmark. GenTreePtr nestedQmark = falseExpr; GenTreePtr cond2Expr; GenTreePtr true2Expr; GenTreePtr false2Expr; if (nestedQmark->gtOper == GT_QMARK) { cond2Expr = nestedQmark->gtGetOp1(); true2Expr = nestedQmark->gtGetOp2()->AsColon()->ThenNode(); false2Expr = nestedQmark->gtGetOp2()->AsColon()->ElseNode(); assert(cond2Expr->gtFlags & GTF_RELOP_QMARK); cond2Expr->gtFlags &= ~GTF_RELOP_QMARK; } else { // This is a rare case that arises when we are doing minopts and encounter isinst of null // gtFoldExpr was still is able to optimize away part of the tree (but not all). // That means it does not match our pattern. // Rather than write code to handle this case, just fake up some nodes to make it match the common // case. Synthesize a comparison that is always true, and for the result-on-true, use the // entire subtree we expected to be the nested question op. cond2Expr = gtNewOperNode(GT_EQ, TYP_INT, gtNewIconNode(0, TYP_I_IMPL), gtNewIconNode(0, TYP_I_IMPL)); true2Expr = nestedQmark; false2Expr = gtNewIconNode(0, TYP_I_IMPL); } assert(false2Expr->OperGet() == trueExpr->OperGet()); // Clear flags as they are now going to be part of JTRUE. assert(condExpr->gtFlags & GTF_RELOP_QMARK); condExpr->gtFlags &= ~GTF_RELOP_QMARK; // Create the chain of blocks. See method header comment. // The order of blocks after this is the following: // block ... asgBlock ... cond1Block ... cond2Block ... helperBlock ... remainderBlock // // We need to remember flags that exist on 'block' that we want to propagate to 'remainderBlock', // if they are going to be cleared by fgSplitBlockAfterStatement(). We currently only do this only // for the GC safe point bit, the logic being that if 'block' was marked gcsafe, then surely // remainderBlock will still be GC safe. unsigned propagateFlags = block->bbFlags & BBF_GC_SAFE_POINT; BasicBlock* remainderBlock = fgSplitBlockAfterStatement(block, stmt); fgRemoveRefPred(remainderBlock, block); // We're going to put more blocks between block and remainderBlock. BasicBlock* helperBlock = fgNewBBafter(BBJ_NONE, block, true); BasicBlock* cond2Block = fgNewBBafter(BBJ_COND, block, true); BasicBlock* cond1Block = fgNewBBafter(BBJ_COND, block, true); BasicBlock* asgBlock = fgNewBBafter(BBJ_NONE, block, true); remainderBlock->bbFlags |= BBF_JMP_TARGET | BBF_HAS_LABEL | propagateFlags; // These blocks are only internal if 'block' is (but they've been set as internal by fgNewBBafter). // If they're not internal, mark them as imported to avoid asserts about un-imported blocks. if ((block->bbFlags & BBF_INTERNAL) == 0) { helperBlock->bbFlags &= ~BBF_INTERNAL; cond2Block->bbFlags &= ~BBF_INTERNAL; cond1Block->bbFlags &= ~BBF_INTERNAL; asgBlock->bbFlags &= ~BBF_INTERNAL; helperBlock->bbFlags |= BBF_IMPORTED; cond2Block->bbFlags |= BBF_IMPORTED; cond1Block->bbFlags |= BBF_IMPORTED; asgBlock->bbFlags |= BBF_IMPORTED; } // Chain the flow correctly. fgAddRefPred(asgBlock, block); fgAddRefPred(cond1Block, asgBlock); fgAddRefPred(cond2Block, cond1Block); fgAddRefPred(helperBlock, cond2Block); fgAddRefPred(remainderBlock, helperBlock); fgAddRefPred(remainderBlock, cond1Block); fgAddRefPred(remainderBlock, cond2Block); cond1Block->bbJumpDest = remainderBlock; cond2Block->bbJumpDest = remainderBlock; // Set the weights; some are guesses. asgBlock->inheritWeight(block); cond1Block->inheritWeight(block); cond2Block->inheritWeightPercentage(cond1Block, 50); helperBlock->inheritWeightPercentage(cond2Block, 50); // Append cond1 as JTRUE to cond1Block GenTreePtr jmpTree = gtNewOperNode(GT_JTRUE, TYP_VOID, condExpr); GenTreePtr jmpStmt = fgNewStmtFromTree(jmpTree, stmt->gtStmt.gtStmtILoffsx); fgInsertStmtAtEnd(cond1Block, jmpStmt); // Append cond2 as JTRUE to cond2Block jmpTree = gtNewOperNode(GT_JTRUE, TYP_VOID, cond2Expr); jmpStmt = fgNewStmtFromTree(jmpTree, stmt->gtStmt.gtStmtILoffsx); fgInsertStmtAtEnd(cond2Block, jmpStmt); // AsgBlock should get tmp = op1 assignment. trueExpr = gtNewTempAssign(dst->AsLclVarCommon()->GetLclNum(), trueExpr); GenTreePtr trueStmt = fgNewStmtFromTree(trueExpr, stmt->gtStmt.gtStmtILoffsx); fgInsertStmtAtEnd(asgBlock, trueStmt); // Since we are adding helper in the JTRUE false path, reverse the cond2 and add the helper. gtReverseCond(cond2Expr); GenTreePtr helperExpr = gtNewTempAssign(dst->AsLclVarCommon()->GetLclNum(), true2Expr); GenTreePtr helperStmt = fgNewStmtFromTree(helperExpr, stmt->gtStmt.gtStmtILoffsx); fgInsertStmtAtEnd(helperBlock, helperStmt); // Finally remove the nested qmark stmt. fgRemoveStmt(block, stmt); #ifdef DEBUG if (verbose) { printf("\nExpanding CastInstOf qmark in BB%02u (after)\n", block->bbNum); fgDispBasicBlocks(block, remainderBlock, true); } #endif // DEBUG } /***************************************************************************** * * Expand a statement with a top level qmark node. There are three cases, based * on whether the qmark has both "true" and "false" arms, or just one of them. * * S0; * C ? T : F; * S1; * * Generates ===> * * bbj_always * +---->------+ * false | | * S0 -->-- ~C -->-- T F -->-- S1 * | | * +--->--------+ * bbj_cond(true) * * ----------------------------------------- * * S0; * C ? T : NOP; * S1; * * Generates ===> * * false * S0 -->-- ~C -->-- T -->-- S1 * | | * +-->-------------+ * bbj_cond(true) * * ----------------------------------------- * * S0; * C ? NOP : F; * S1; * * Generates ===> * * false * S0 -->-- C -->-- F -->-- S1 * | | * +-->------------+ * bbj_cond(true) * * If the qmark assigns to a variable, then create tmps for "then" * and "else" results and assign the temp to the variable as a writeback step. */ void Compiler::fgExpandQmarkStmt(BasicBlock* block, GenTreePtr stmt) { GenTreePtr expr = stmt->gtStmt.gtStmtExpr; // Retrieve the Qmark node to be expanded. GenTreePtr dst = nullptr; GenTreePtr qmark = fgGetTopLevelQmark(expr, &dst); if (qmark == nullptr) { return; } if (qmark->gtFlags & GTF_QMARK_CAST_INSTOF) { fgExpandQmarkForCastInstOf(block, stmt); return; } #ifdef DEBUG if (verbose) { printf("\nExpanding top-level qmark in BB%02u (before)\n", block->bbNum); fgDispBasicBlocks(block, block, true); } #endif // DEBUG // Retrieve the operands. GenTreePtr condExpr = qmark->gtGetOp1(); GenTreePtr trueExpr = qmark->gtGetOp2()->AsColon()->ThenNode(); GenTreePtr falseExpr = qmark->gtGetOp2()->AsColon()->ElseNode(); assert(condExpr->gtFlags & GTF_RELOP_QMARK); condExpr->gtFlags &= ~GTF_RELOP_QMARK; assert(!varTypeIsFloating(condExpr->TypeGet())); bool hasTrueExpr = (trueExpr->OperGet() != GT_NOP); bool hasFalseExpr = (falseExpr->OperGet() != GT_NOP); assert(hasTrueExpr || hasFalseExpr); // We expect to have at least one arm of the qmark! // Create remainder, cond and "else" blocks. After this, the blocks are in this order: // block ... condBlock ... elseBlock ... remainderBlock // // We need to remember flags that exist on 'block' that we want to propagate to 'remainderBlock', // if they are going to be cleared by fgSplitBlockAfterStatement(). We currently only do this only // for the GC safe point bit, the logic being that if 'block' was marked gcsafe, then surely // remainderBlock will still be GC safe. unsigned propagateFlags = block->bbFlags & BBF_GC_SAFE_POINT; BasicBlock* remainderBlock = fgSplitBlockAfterStatement(block, stmt); fgRemoveRefPred(remainderBlock, block); // We're going to put more blocks between block and remainderBlock. BasicBlock* condBlock = fgNewBBafter(BBJ_COND, block, true); BasicBlock* elseBlock = fgNewBBafter(BBJ_NONE, condBlock, true); // These blocks are only internal if 'block' is (but they've been set as internal by fgNewBBafter). // If they're not internal, mark them as imported to avoid asserts about un-imported blocks. if ((block->bbFlags & BBF_INTERNAL) == 0) { condBlock->bbFlags &= ~BBF_INTERNAL; elseBlock->bbFlags &= ~BBF_INTERNAL; condBlock->bbFlags |= BBF_IMPORTED; elseBlock->bbFlags |= BBF_IMPORTED; } remainderBlock->bbFlags |= BBF_JMP_TARGET | BBF_HAS_LABEL | propagateFlags; condBlock->inheritWeight(block); fgAddRefPred(condBlock, block); fgAddRefPred(elseBlock, condBlock); fgAddRefPred(remainderBlock, elseBlock); BasicBlock* thenBlock = nullptr; if (hasTrueExpr && hasFalseExpr) { // bbj_always // +---->------+ // false | | // S0 -->-- ~C -->-- T F -->-- S1 // | | // +--->--------+ // bbj_cond(true) // gtReverseCond(condExpr); condBlock->bbJumpDest = elseBlock; thenBlock = fgNewBBafter(BBJ_ALWAYS, condBlock, true); thenBlock->bbJumpDest = remainderBlock; if ((block->bbFlags & BBF_INTERNAL) == 0) { thenBlock->bbFlags &= ~BBF_INTERNAL; thenBlock->bbFlags |= BBF_IMPORTED; } elseBlock->bbFlags |= (BBF_JMP_TARGET | BBF_HAS_LABEL); fgAddRefPred(thenBlock, condBlock); fgAddRefPred(remainderBlock, thenBlock); thenBlock->inheritWeightPercentage(condBlock, 50); elseBlock->inheritWeightPercentage(condBlock, 50); } else if (hasTrueExpr) { // false // S0 -->-- ~C -->-- T -->-- S1 // | | // +-->-------------+ // bbj_cond(true) // gtReverseCond(condExpr); condBlock->bbJumpDest = remainderBlock; fgAddRefPred(remainderBlock, condBlock); // Since we have no false expr, use the one we'd already created. thenBlock = elseBlock; elseBlock = nullptr; thenBlock->inheritWeightPercentage(condBlock, 50); } else if (hasFalseExpr) { // false // S0 -->-- C -->-- F -->-- S1 // | | // +-->------------+ // bbj_cond(true) // condBlock->bbJumpDest = remainderBlock; fgAddRefPred(remainderBlock, condBlock); elseBlock->inheritWeightPercentage(condBlock, 50); } GenTreePtr jmpTree = gtNewOperNode(GT_JTRUE, TYP_VOID, qmark->gtGetOp1()); GenTreePtr jmpStmt = fgNewStmtFromTree(jmpTree, stmt->gtStmt.gtStmtILoffsx); fgInsertStmtAtEnd(condBlock, jmpStmt); // Remove the original qmark statement. fgRemoveStmt(block, stmt); // Since we have top level qmarks, we either have a dst for it in which case // we need to create tmps for true and falseExprs, else just don't bother // assigning. unsigned lclNum = BAD_VAR_NUM; if (dst != nullptr) { assert(dst->gtOper == GT_LCL_VAR); lclNum = dst->gtLclVar.gtLclNum; } else { assert(qmark->TypeGet() == TYP_VOID); } if (hasTrueExpr) { if (dst != nullptr) { trueExpr = gtNewTempAssign(lclNum, trueExpr); } GenTreePtr trueStmt = fgNewStmtFromTree(trueExpr, stmt->gtStmt.gtStmtILoffsx); fgInsertStmtAtEnd(thenBlock, trueStmt); } // Assign the falseExpr into the dst or tmp, insert in elseBlock if (hasFalseExpr) { if (dst != nullptr) { falseExpr = gtNewTempAssign(lclNum, falseExpr); } GenTreePtr falseStmt = fgNewStmtFromTree(falseExpr, stmt->gtStmt.gtStmtILoffsx); fgInsertStmtAtEnd(elseBlock, falseStmt); } #ifdef DEBUG if (verbose) { printf("\nExpanding top-level qmark in BB%02u (after)\n", block->bbNum); fgDispBasicBlocks(block, remainderBlock, true); } #endif // DEBUG } /***************************************************************************** * * Expand GT_QMARK nodes from the flow graph into basic blocks. * */ void Compiler::fgExpandQmarkNodes() { if (compQmarkUsed) { for (BasicBlock* block = fgFirstBB; block; block = block->bbNext) { for (GenTreePtr stmt = block->bbTreeList; stmt; stmt = stmt->gtNext) { GenTreePtr expr = stmt->gtStmt.gtStmtExpr; #ifdef DEBUG fgPreExpandQmarkChecks(expr); #endif fgExpandQmarkStmt(block, stmt); } } #ifdef DEBUG fgPostExpandQmarkChecks(); #endif } compQmarkRationalized = true; } #ifdef DEBUG /***************************************************************************** * * Make sure we don't have any more GT_QMARK nodes. * */ void Compiler::fgPostExpandQmarkChecks() { for (BasicBlock* block = fgFirstBB; block; block = block->bbNext) { for (GenTreePtr stmt = block->bbTreeList; stmt; stmt = stmt->gtNext) { GenTreePtr expr = stmt->gtStmt.gtStmtExpr; fgWalkTreePre(&expr, Compiler::fgAssertNoQmark, NULL); } } } #endif /***************************************************************************** * * Transform all basic blocks for codegen. */ void Compiler::fgMorph() { noway_assert(!compIsForInlining()); // Inlinee's compiler should never reach here. fgOutgoingArgTemps = nullptr; #ifdef DEBUG if (verbose) printf("*************** In fgMorph()\n"); if (verboseTrees) fgDispBasicBlocks(true); #endif // DEBUG // Insert call to class constructor as the first basic block if // we were asked to do so. if (info.compCompHnd->initClass(NULL /* field */, info.compMethodHnd /* method */, impTokenLookupContextHandle /* context */) & CORINFO_INITCLASS_USE_HELPER) { fgEnsureFirstBBisScratch(); fgInsertStmtAtBeg(fgFirstBB, fgInitThisClass()); } #ifdef DEBUG if (opts.compGcChecks) { for (unsigned i = 0; i < info.compArgsCount; i++) { if (lvaTable[i].TypeGet() == TYP_REF) { // confirm that the argument is a GC pointer (for debugging (GC stress)) GenTreePtr op = gtNewLclvNode(i, TYP_REF); GenTreeArgList* args = gtNewArgList(op); op = gtNewHelperCallNode(CORINFO_HELP_CHECK_OBJ, TYP_VOID, 0, args); fgEnsureFirstBBisScratch(); fgInsertStmtAtEnd(fgFirstBB, op); } } } if (opts.compStackCheckOnRet) { lvaReturnEspCheck = lvaGrabTempWithImplicitUse(false DEBUGARG("ReturnEspCheck")); lvaTable[lvaReturnEspCheck].lvType = TYP_INT; } if (opts.compStackCheckOnCall) { lvaCallEspCheck = lvaGrabTempWithImplicitUse(false DEBUGARG("CallEspCheck")); lvaTable[lvaCallEspCheck].lvType = TYP_INT; } #endif // DEBUG /* Filter out unimported BBs */ fgRemoveEmptyBlocks(); /* Add any internal blocks/trees we may need */ fgAddInternal(); #if OPT_BOOL_OPS fgMultipleNots = false; #endif #ifdef DEBUG /* Inliner could add basic blocks. Check that the flowgraph data is up-to-date */ fgDebugCheckBBlist(false, false); #endif // DEBUG /* Inline */ fgInline(); #if 0 JITDUMP("trees after inlining\n"); DBEXEC(VERBOSE, fgDispBasicBlocks(true)); #endif RecordStateAtEndOfInlining(); // Record "start" values for post-inlining cycles and elapsed time. #ifdef DEBUG /* Inliner could add basic blocks. Check that the flowgraph data is up-to-date */ fgDebugCheckBBlist(false, false); #endif // DEBUG /* For x64 and ARM64 we need to mark irregular parameters early so that they don't get promoted */ fgMarkImplicitByRefArgs(); /* Promote struct locals if necessary */ fgPromoteStructs(); /* Now it is the time to figure out what locals have address-taken. */ fgMarkAddressExposedLocals(); #ifdef DEBUG /* Now that locals have address-taken marked, we can safely apply stress. */ lvaStressLclFld(); fgStress64RsltMul(); #endif // DEBUG /* Morph the trees in all the blocks of the method */ fgMorphBlocks(); #if 0 JITDUMP("trees after fgMorphBlocks\n"); DBEXEC(VERBOSE, fgDispBasicBlocks(true)); #endif /* Decide the kind of code we want to generate */ fgSetOptions(); fgExpandQmarkNodes(); #ifdef DEBUG compCurBB = 0; #endif // DEBUG } /***************************************************************************** * * Promoting struct locals */ void Compiler::fgPromoteStructs() { #ifdef DEBUG if (verbose) printf("*************** In fgPromoteStructs()\n"); #endif // DEBUG if (!opts.OptEnabled(CLFLG_STRUCTPROMOTE)) return; if (fgNoStructPromotion) return; #if 0 // The code in this #if has been useful in debugging struct promotion issues, by // enabling selective enablement of the struct promotion optimization according to // method hash. #ifdef DEBUG unsigned methHash = info.compMethodHash(); char* lostr = getenv("structpromohashlo"); unsigned methHashLo = 0; if (lostr != NULL) { sscanf_s(lostr, "%x", &methHashLo); } char* histr = getenv("structpromohashhi"); unsigned methHashHi = UINT32_MAX; if (histr != NULL) { sscanf_s(histr, "%x", &methHashHi); } if (methHash < methHashLo || methHash > methHashHi) { return; } else { printf("Promoting structs for method %s, hash = 0x%x.\n", info.compFullName, info.compMethodHash()); printf(""); // in our logic this causes a flush } #endif // DEBUG #endif // 0 if (info.compIsVarArgs) return; if (getNeedsGSSecurityCookie()) return; // The lvaTable might grow as we grab temps. Make a local copy here. unsigned startLvaCount = lvaCount; // // Loop through the original lvaTable. Looking for struct locals to be promoted. // lvaStructPromotionInfo structPromotionInfo; for (unsigned lclNum = 0; lclNum < startLvaCount; lclNum++) { LclVarDsc* varDsc = &lvaTable[lclNum]; // Don't promote if we have reached the tracking limit. if (lvaHaveManyLocals()) { JITDUMP("Stopped promoting struct fields, due to too many locals.\n"); break; } #if FEATURE_MULTIREG_ARGS_OR_RET if (varDsc->lvIsMultiRegArgOrRet) { JITDUMP("Skipping V%02u: marked lvIsMultiRegArgOrRet.\n", lclNum); continue; } #endif // FEATURE_MULTIREG_ARGS_OR_RET #ifdef FEATURE_SIMD if (varDsc->lvSIMDType && varDsc->lvUsedInSIMDIntrinsic) { // If we have marked this as lvUsedInSIMDIntrinsic, then we do not want to promote // its fields. Instead, we will attempt to enregister the entire struct. // Note, however, that if the code below does not decide to promote this struct, // we will still set lvRegStruct if its fields have not been accessed. varDsc->lvRegStruct = true; } else #endif // FEATURE_SIMD if (varTypeIsStruct(varDsc)) { lvaCanPromoteStructVar(lclNum, &structPromotionInfo); if (structPromotionInfo.canPromote) { // We *can* promote; *should* we promote? // We should only do so if promotion has potential savings. One source of savings // is if a field of the struct is accessed, since this access will be turned into // an access of the corresponding promoted field variable. Even if there are no // field accesses, but only block-level operations on the whole struct, if the struct // has only one or two fields, then doing those block operations field-wise is probably faster // than doing a whole-variable block operation (e.g., a hardware "copy loop" on x86). // So if no fields are accessed independently, and there are three or more fields, // then do not promote. if (structPromotionInfo.fieldCnt > 2 && !varDsc->lvFieldAccessed) { JITDUMP("Not promoting promotable struct local V%02u: #fields = %d, fieldAccessed = %d.\n", lclNum, structPromotionInfo.fieldCnt, varDsc->lvFieldAccessed); continue; } #if defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_) // TODO-PERF - Only do this when the LclVar is used in an argument context // TODO-ARM64 - HFA support should also eliminate the need for this. // // For now we currently don't promote structs with a single float field // Promoting it can cause us to shuffle it back and forth between the int and // the float regs when it is used as a argument, which is very expensive for XARCH // if (structPromotionInfo.fieldCnt==1 && varTypeIsFloating(structPromotionInfo.fields[0].fldType)) { JITDUMP("Not promoting promotable struct local V%02u: #fields = %d because it is a struct with single float field.\n", lclNum, structPromotionInfo.fieldCnt); continue; } #endif // _TARGET_AMD64_ || _TARGET_ARM64_ #if FEATURE_MULTIREG_ARGS #if defined(_TARGET_ARM64_) // // For now we currently don't promote structs that could be passed in registers // if (varDsc->lvIsMultiregStruct()) { JITDUMP("Not promoting promotable struct local V%02u (size==%d): ", lclNum, lvaLclExactSize(lclNum)); continue; } #endif // _TARGET_ARM64_ #endif // FEATURE_MULTIREG_ARGS if (varDsc->lvIsParam) { if (structPromotionInfo.fieldCnt != 1) { JITDUMP("Not promoting promotable struct local V%02u, because lvIsParam are true and #fields = %d.\n", lclNum, structPromotionInfo.fieldCnt); continue; } } // // If the lvRefCnt is zero and we have a struct promoted parameter we can end up with an extra store of the the // incoming register into the stack frame slot. // In that case, we would like to avoid promortion. // However we haven't yet computed the lvRefCnt values so we can't do that. // #if 0 // Often-useful debugging code: if you've narrowed down a struct-promotion problem to a single // method, this allows you to select a subset of the vars to promote (by 1-based ordinal number). static int structPromoVarNum = 0; structPromoVarNum++; if (atoi(getenv("structpromovarnumlo")) <= structPromoVarNum && structPromoVarNum <= atoi(getenv("structpromovarnumhi"))) #endif // 0 { // Promote the this struct local var. lvaPromoteStructVar(lclNum, &structPromotionInfo); #ifdef _TARGET_ARM_ if (structPromotionInfo.requiresScratchVar) { // Ensure that the scratch variable is allocated, in case we // pass a promoted struct as an argument. if (lvaPromotedStructAssemblyScratchVar == BAD_VAR_NUM) { lvaPromotedStructAssemblyScratchVar = lvaGrabTempWithImplicitUse(false DEBUGARG("promoted struct assembly scratch var.")); lvaTable[lvaPromotedStructAssemblyScratchVar].lvType = TYP_I_IMPL; } } #endif // _TARGET_ARM_ } } #ifdef FEATURE_SIMD else if (varDsc->lvSIMDType && !varDsc->lvFieldAccessed) { // Even if we have not used this in a SIMD intrinsic, if it is not being promoted, // we will treat it as a reg struct. varDsc->lvRegStruct = true; } #endif // FEATURE_SIMD } } } Compiler::fgWalkResult Compiler::fgMorphStructField(GenTreePtr tree, fgWalkData* fgWalkPre) { noway_assert(tree->OperGet() == GT_FIELD); noway_assert(tree->gtFlags & GTF_GLOB_REF); GenTreePtr objRef = tree->gtField.gtFldObj; /* Is this an instance data member? */ if (objRef) { if (objRef->gtOper == GT_ADDR) { GenTreePtr obj = objRef->gtOp.gtOp1; if (obj->gtOper == GT_LCL_VAR) { unsigned lclNum = obj->gtLclVarCommon.gtLclNum; LclVarDsc* varDsc = &lvaTable[lclNum]; if (varTypeIsStruct(obj)) { if (varDsc->lvPromoted) { // Promoted struct unsigned fldOffset = tree->gtField.gtFldOffset; unsigned fieldLclIndex = lvaGetFieldLocal(varDsc, fldOffset); tree->SetOper(GT_LCL_VAR); tree->gtLclVarCommon.SetLclNum(fieldLclIndex); tree->gtType = lvaTable[fieldLclIndex].TypeGet(); tree->gtFlags &= GTF_NODE_MASK; tree->gtFlags &= ~GTF_GLOB_REF; GenTreePtr parent = fgWalkPre->parentStack->Index(1); if ((parent->gtOper == GT_ASG) && (parent->gtOp.gtOp1 == tree)) { tree->gtFlags |= GTF_VAR_DEF; tree->gtFlags |= GTF_DONT_CSE; } #ifdef DEBUG if (verbose) { printf("Replacing the field in promoted struct with a local var:\n"); fgWalkPre->printModified = true; } #endif // DEBUG return WALK_SKIP_SUBTREES; } } else { // Normed struct // A "normed struct" is a struct that the VM tells us is a basic type. This can only happen if // the struct contains a single element, and that element is 4 bytes (on x64 it can also be 8 bytes). // Normally, the type of the local var and the type of GT_FIELD are equivalent. However, there // is one extremely rare case where that won't be true. An enum type is a special value type // that contains exactly one element of a primitive integer type (that, for CLS programs is named "value__"). // The VM tells us that a local var of that enum type is the primitive type of the enum's single field. // It turns out that it is legal for IL to access this field using ldflda or ldfld. For example: // // .class public auto ansi sealed mynamespace.e_t extends [mscorlib]System.Enum // { // .field public specialname rtspecialname int16 value__ // .field public static literal valuetype mynamespace.e_t one = int16(0x0000) // } // .method public hidebysig static void Main() cil managed // { // .locals init (valuetype mynamespace.e_t V_0) // ... // ldloca.s V_0 // ldflda int16 mynamespace.e_t::value__ // ... // } // // Normally, compilers will not generate the ldflda, since it is superfluous. // // In the example, the lclVar is short, but the JIT promotes all trees using this local to the // "actual type", that is, INT. But the GT_FIELD is still SHORT. So, in the case of a type // mismatch like this, don't do this morphing. The local var may end up getting marked as // address taken, and the appropriate SHORT load will be done from memory in that case. if (tree->TypeGet() == obj->TypeGet()) { tree->ChangeOper(GT_LCL_VAR); tree->gtLclVarCommon.SetLclNum(lclNum); tree->gtFlags &= GTF_NODE_MASK; GenTreePtr parent = fgWalkPre->parentStack->Index(1); if ((parent->gtOper == GT_ASG) && (parent->gtOp.gtOp1 == tree)) { tree->gtFlags |= GTF_VAR_DEF; tree->gtFlags |= GTF_DONT_CSE; } #ifdef DEBUG if (verbose) { printf("Replacing the field in normed struct with the local var:\n"); fgWalkPre->printModified = true; } #endif // DEBUG return WALK_SKIP_SUBTREES; } } } } } return WALK_CONTINUE; } Compiler::fgWalkResult Compiler::fgMorphLocalField(GenTreePtr tree, fgWalkData* fgWalkPre) { noway_assert(tree->OperGet() == GT_LCL_FLD); unsigned lclNum = tree->gtLclFld.gtLclNum; LclVarDsc* varDsc = &lvaTable[lclNum]; if (varTypeIsStruct(varDsc) && (varDsc->lvPromoted)) { // Promoted struct unsigned fldOffset = tree->gtLclFld.gtLclOffs; unsigned fieldLclIndex = 0; LclVarDsc* fldVarDsc = NULL; if (fldOffset != BAD_VAR_NUM) { fieldLclIndex = lvaGetFieldLocal(varDsc, fldOffset); fldVarDsc = &lvaTable[fieldLclIndex]; } if (fldOffset != BAD_VAR_NUM && genTypeSize(fldVarDsc->TypeGet()) == genTypeSize(tree->gtType) #ifdef _TARGET_X86_ && varTypeIsFloating(fldVarDsc->TypeGet()) == varTypeIsFloating(tree->gtType) #endif ) { // There is an existing sub-field we can use tree->gtLclFld.SetLclNum(fieldLclIndex); // We need to keep the types 'compatible'. If we can switch back to a GT_LCL_VAR assert(varTypeIsIntegralOrI(tree->TypeGet())); if (varTypeCanReg(fldVarDsc->TypeGet())) { // If the type is integer-ish, then we can use it as-is tree->ChangeOper(GT_LCL_VAR); assert(tree->gtLclVarCommon.gtLclNum == fieldLclIndex); tree->gtType = fldVarDsc->TypeGet(); #ifdef DEBUG if (verbose) { printf("Replacing the GT_LCL_FLD in promoted struct with a local var:\n"); fgWalkPre->printModified = true; } #endif // DEBUG } GenTreePtr parent = fgWalkPre->parentStack->Index(1); if ((parent->gtOper == GT_ASG) && (parent->gtOp.gtOp1 == tree)) { tree->gtFlags |= GTF_VAR_DEF; tree->gtFlags |= GTF_DONT_CSE; } } else { // There is no existing field that has all the parts that we need // So we must ensure that the struct lives in memory. lvaSetVarDoNotEnregister(lclNum DEBUG_ARG(DNER_LocalField)); #ifdef DEBUG // We can't convert this guy to a float because he really does have his // address taken.. varDsc->lvKeepType = 1; #endif // DEBUG } return WALK_SKIP_SUBTREES; } return WALK_CONTINUE; } /***************************************************************************** * * Mark irregular parameters. For x64 this is 3, 5, 6, 7, >8 byte structs that are passed by reference. * For ARM64, this is structs larger than 16 bytes that are passed by reference. */ void Compiler::fgMarkImplicitByRefArgs() { #if defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_) #ifdef DEBUG if (verbose) printf("\n*************** In fgMarkImplicitByRefs()\n"); #endif // DEBUG for (unsigned lclNum = 0; lclNum < lvaCount; lclNum++) { LclVarDsc* varDsc = &lvaTable[lclNum]; assert(!varDsc->lvPromoted); // Called in the wrong order? if (varDsc->lvIsParam && varTypeIsStruct(varDsc)) { size_t size; if (varDsc->lvSize() > REGSIZE_BYTES) { size = varDsc->lvSize(); } else { CORINFO_CLASS_HANDLE typeHnd = varDsc->lvVerTypeInfo.GetClassHandle(); size = info.compCompHnd->getClassSize(typeHnd); } #if !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING) #if defined(_TARGET_AMD64_) if (size > REGSIZE_BYTES || (size & (size - 1)) != 0) #elif defined(_TARGET_ARM64_) if (size > 16) #endif { // Previously nobody was ever setting lvIsParam and lvIsTemp on the same local // So I am now using it to indicate that this is one of the weird implicit // by ref locals. // The address taken cleanup will look for references to locals marked like // this, and transform them appropriately. varDsc->lvIsTemp = 1; // Also marking them as BYREF will hide them from struct promotion. varDsc->lvType = TYP_BYREF; varDsc->lvRefCnt = 0; // Since this previously was a TYP_STRUCT and we have changed it to a TYP_BYREF // make sure that the following flag is not set as these will force SSA to // exclude tracking/enregistering these LclVars. (see fgExcludeFromSsa) // varDsc->lvOverlappingFields = 0; // This flag could have been set, clear it. #ifdef DEBUG // This should not be converted to a double in stress mode, // because it is really a pointer varDsc->lvKeepType = 1; #endif // DEBUG } #endif // !FEATURE_UNIX_AMD64_STRUCT_PASSING } } #endif // _TARGET_AMD64_ || _TARGET_ARM64_ } /***************************************************************************** * * Morph irregular parameters * for x64 and ARM64 this means turning them into byrefs, adding extra indirs. */ bool Compiler::fgMorphImplicitByRefArgs(GenTreePtr tree, fgWalkData* fgWalkPre) { #if !defined(_TARGET_AMD64_) && !defined(_TARGET_ARM64_) return false; #else // _TARGET_AMD64_ || _TARGET_ARM64_ assert((tree->gtOper == GT_LCL_VAR) || ((tree->gtOper == GT_ADDR) && (tree->gtOp.gtOp1->gtOper == GT_LCL_VAR))); bool isAddr = (tree->gtOper == GT_ADDR); GenTreePtr lclVarTree = isAddr ? tree->gtOp.gtOp1 : tree; unsigned lclNum = lclVarTree->gtLclVarCommon.gtLclNum; LclVarDsc* lclVarDsc = &lvaTable[lclNum]; if (!lvaIsImplicitByRefLocal(lclNum)) { // We only need to tranform the 'marked' implicit by ref parameters return false; } // The SIMD transformation to coalesce contiguous references to SIMD vector fields will // re-invoke the traversal to mark address-taken locals. // So, we may encounter a tree that has already been transformed to TYP_BYREF. // If we do, leave it as-is. if (!varTypeIsStruct(lclVarTree)) { assert(lclVarTree->TypeGet() == TYP_BYREF); return false; } // We are overloading the lvRefCnt field here because real ref counts have not been set. lclVarDsc->lvRefCnt++; if (isAddr) { // change &X into just plain X tree->CopyFrom(lclVarTree, this); tree->gtType = TYP_BYREF; #ifdef DEBUG if (verbose) { printf("Replacing address of implicit by ref struct parameter with byref:\n"); fgWalkPre->printModified = true; } #endif // DEBUG } else { // Change X into *X // First, save the original type, then change the tree type to TYP_BYREF (otherwise we // will get an assert when we try to clone the lclVar node because the lclVar is now TYP_BYREF // and the types have to match). The reason we clone the lclVar is that we don't pass a // possible-modified tree back to the caller, so we modify the original lclVar node in-place // to the GT_IND. var_types structType = tree->gtType; lclVarTree = gtClone(tree); // Now, set the types appropriately. lclVarTree->gtType = TYP_BYREF; tree->gtType = structType; // Now, "insert" the GT_IND by changing the oper of the original node and setting its op1. tree->SetOper(GT_IND); tree->gtOp.gtOp1 = lclVarTree; // TODO-CQ: If the VM ever stops violating the ABI and passing heap references // we could remove TGTANYWHERE tree->gtFlags = ((tree->gtFlags & GTF_COMMON_MASK) | GTF_IND_TGTANYWHERE); #ifdef DEBUG if (verbose) { printf("Replacing value of implicit by ref struct parameter with indir of parameter:\n"); gtDispTree(tree, nullptr, nullptr, true); fgWalkPre->printModified = true; } #endif // DEBUG } return true; #endif // _TARGET_AMD64_ || _TARGET_ARM64_ } // An "AddrExposedContext" expresses the calling context in which an address expression occurs. enum AddrExposedContext { AXC_None, // None of the below seen yet. AXC_Ind, // The address being computed is to be dereferenced. AXC_Addr, // We're computing a raw address (not dereferenced, at least not immediately). AXC_IndWide, // A block operation dereferenced an address referencing more bytes than the address // addresses -- if the address addresses a field of a struct local, we need to consider // the entire local address taken (not just the field). AXC_AddrWide, // The address being computed will be dereferenced by a block operation that operates // on more bytes than the width of the storage location addressed. If this is a // field of a promoted struct local, declare the entire struct local address-taken. AXC_InitBlk, // An GT_INITBLK is the immediate parent. The first argument is in an IND context. AXC_CopyBlk, // An GT_COPYBLK is the immediate parent. The first argument is in a GT_LIST, whose // args should be evaluated in an IND context. AXC_IndAdd, // A GT_ADD is the immediate parent, and it was evaluated in an IND contxt. // If one arg is a constant int, evaluate the other in an IND context. Otherwise, none. }; typedef ArrayStack<AddrExposedContext> AXCStack; // We use pre-post to simulate passing an argument in a recursion, via a stack. Compiler::fgWalkResult Compiler::fgMarkAddrTakenLocalsPostCB(GenTreePtr* pTree, fgWalkData* fgWalkPre) { AXCStack* axcStack = reinterpret_cast<AXCStack*>(fgWalkPre->pCallbackData); (void)axcStack->Pop(); return WALK_CONTINUE; } Compiler::fgWalkResult Compiler::fgMarkAddrTakenLocalsPreCB(GenTreePtr* pTree, fgWalkData* fgWalkPre) { GenTreePtr tree = *pTree; Compiler* comp = fgWalkPre->compiler; AXCStack* axcStack = reinterpret_cast<AXCStack*>(fgWalkPre->pCallbackData); AddrExposedContext axc = axcStack->Top(); // In some situations, we have to figure out what the effective context is in which to // evaluate the current tree, depending on which argument position it is in its parent. // If the parent was an initblock, and this is its first argument, we're in // and "ind" context. switch (axc) { case AXC_InitBlk: case AXC_CopyBlk: { // In both cases, the second argument is an integer struct size. That should have a "none" context. // The first argument is a GT_LIST. For GT_COPYBLK, both args of the list are addresses // that are dereferenced; for GT_INITBLK, the first is. We pass "axc" to the GT_LIST; // which will pass it to its arguments; these will decide whether they're in an Ind context // depending on "axc" and which argument they are. // A GT_INITBLK's first argument is a GT_LIST, whose first argument is an address // that should be considered to be dereferenced, and whose second argument the integer // (byte) value to fill the block with. The second argument of the GT_INITBLK is also // an integer, the block size. GenTreePtr parent = fgWalkPre->parentStack->Index(1); if (parent->gtOp.gtOp2 == tree && parent->OperIsBlkOp()) { axc = AXC_None; } else if (parent->OperGet() == GT_LIST) { genTreeOps axcOper = fgWalkPre->parentStack->Index(2)->OperGet(); assert((axc == AXC_InitBlk && axcOper == GT_INITBLK) || (axc == AXC_CopyBlk && GenTree::OperIsCopyBlkOp(axcOper))); // The block operation will derefence its argument(s) -- usually. If the size of the initblk // or copyblk exceeds the size of a storage location whose address is used as one of the // arguments, then we have to consider that storage location (indeed, it's underlying containing // location) to be address taken. So get the width of the initblk or copyblk. GenTreePtr widthNode = fgWalkPre->parentStack->Index(2)->gtOp.gtOp2; unsigned width = UINT_MAX; // If it's not a constant, assume it's maximally big. if (widthNode->IsCnsIntOrI()) { if (widthNode->IsIconHandle()) { // If it's a handle, it must be a class handle. We only create such block operations // for initialization of struct types, so the type of the argument(s) will match this // type, by construction. Set the width to zero to make sure nothing fits in it. assert(widthNode->IsIconHandle(GTF_ICON_CLASS_HDL)); width = 0; } else { ssize_t swidth = widthNode->gtIntConCommon.IconValue(); assert(swidth > 0); // Well-formedness of the block operation node... width = unsigned(swidth); } } if (parent->gtOp.gtOp1 == tree) { // First argument is (potentially) dereferenced by both kinds of block operations. if (tree->OperGet() == GT_ADDR && !comp->fgFitsInOrNotLoc(tree->gtOp.gtOp1, width)) { axc = AXC_IndWide; } else { axc = AXC_Ind; } } else if (axc == AXC_CopyBlk) { assert(parent->gtOp.gtOp2 == tree); if (tree->OperGet() == GT_ADDR && !comp->fgFitsInOrNotLoc(tree->gtOp.gtOp1, width)) { axc = AXC_IndWide; } else { axc = AXC_Ind; } } else { axc = AXC_None; } } } break; case AXC_IndAdd: { GenTreePtr parent = fgWalkPre->parentStack->Index(1); assert(parent->OperGet() == GT_ADD); // Is one of the args a constant representing a field offset, // and is this the other? If so, Ind context. if (parent->gtOp.gtOp1->IsCnsIntOrI() && parent->gtOp.gtOp2 == tree) { axc = AXC_Ind; } else if (parent->gtOp.gtOp2->IsCnsIntOrI() && parent->gtOp.gtOp1 == tree) { axc = AXC_Ind; } else { axc = AXC_None; } } break; default: break; } // Now recurse properly for the tree. switch (tree->gtOper) { case GT_IND: case GT_OBJ: if (axc != AXC_Addr) { axcStack->Push(AXC_Ind); } else { axcStack->Push(AXC_None); } return WALK_CONTINUE; case GT_INITBLK: axcStack->Push(AXC_InitBlk); return WALK_CONTINUE; case GT_COPYOBJ: case GT_COPYBLK: axcStack->Push(AXC_CopyBlk); return WALK_CONTINUE; case GT_LIST: if (axc == AXC_InitBlk || axc == AXC_CopyBlk) { axcStack->Push(axc); } else { axcStack->Push(AXC_None); } return WALK_CONTINUE; case GT_INDEX: // Taking the address of an array element never takes the address of a local. axcStack->Push(AXC_None); return WALK_CONTINUE; case GT_ADDR: // If we have ADDR(lcl), and "lcl" is an implicit byref parameter, fgMorphImplicitByRefArgs will // convert to just "lcl". This is never an address-context use, since the local is already a // byref after this transformation. if (tree->gtOp.gtOp1->OperGet() == GT_LCL_VAR && comp->fgMorphImplicitByRefArgs(tree, fgWalkPre)) { // Push something to keep the PostCB, which will pop it, happy. axcStack->Push(AXC_None); // In the first case, tree may no longer be a leaf, but we're done with it; is a leaf in the second case. return WALK_SKIP_SUBTREES; } // Otherwise... #ifdef FEATURE_SIMD if (tree->gtOp.gtOp1->OperGet() == GT_SIMD) { axcStack->Push(AXC_None); } else #endif // FEATURE_SIMD if (axc == AXC_Ind) { axcStack->Push(AXC_None); } else if (axc == AXC_IndWide) { axcStack->Push(AXC_AddrWide); } else { assert(axc == AXC_None); axcStack->Push(AXC_Addr); } return WALK_CONTINUE; case GT_FIELD: // First, handle a couple of special cases: field of promoted struct local, field // of "normed" struct. if (comp->fgMorphStructField(tree, fgWalkPre) == WALK_SKIP_SUBTREES) { // It (may have) replaced the field with a local var or local field. If we're in an addr context, // label it addr-taken. if (tree->OperIsLocal() && (axc == AXC_Addr || axc == AXC_AddrWide)) { unsigned lclNum = tree->gtLclVarCommon.gtLclNum; comp->lvaSetVarAddrExposed(lclNum); if (axc == AXC_AddrWide) { LclVarDsc* varDsc = &comp->lvaTable[lclNum]; if (varDsc->lvIsStructField) { comp->lvaSetVarAddrExposed(varDsc->lvParentLcl); } } } // Push something to keep the PostCB, which will pop it, happy. axcStack->Push(AXC_None); return WALK_SKIP_SUBTREES; } else { // GT_FIELD is an implicit deref. if (axc == AXC_Addr) { axcStack->Push(AXC_None); } else if (axc == AXC_AddrWide) { axcStack->Push(AXC_IndWide); } else { axcStack->Push(AXC_Ind); } return WALK_CONTINUE; } case GT_LCL_FLD: { assert(axc != AXC_Addr); // This recognizes certain forms, and does all the work. In that case, returns WALK_SKIP_SUBTREES, // else WALK_CONTINUE. We do the same here. fgWalkResult res = comp->fgMorphLocalField(tree, fgWalkPre); if (res == WALK_SKIP_SUBTREES && tree->OperGet() == GT_LCL_VAR && (axc == AXC_Addr || axc == AXC_AddrWide)) { unsigned lclNum = tree->gtLclVarCommon.gtLclNum; comp->lvaSetVarAddrExposed(lclNum); if (axc == AXC_AddrWide) { LclVarDsc* varDsc = &comp->lvaTable[lclNum]; if (varDsc->lvIsStructField) { comp->lvaSetVarAddrExposed(varDsc->lvParentLcl); } } } // Must push something; if res is WALK_SKIP_SUBTREES, doesn't matter // what, but something to be popped by the post callback. If we're going // to analyze children, the LCL_FLD creates an Ind context, so use that. axcStack->Push(AXC_Ind); return res; } case GT_LCL_VAR: // On some architectures, some arguments are passed implicitly by reference. // Modify the trees to reflect that, if this local is one of those. if (comp->fgMorphImplicitByRefArgs(tree, fgWalkPre)) { // We can't be in an address context; the ADDR(lcl), where lcl is an implicit byref param, was // handled earlier. (And we can't have added anything to this address, since it was implicit.) assert(axc != AXC_Addr); } else { if (axc == AXC_Addr || axc == AXC_AddrWide) { unsigned lclNum = tree->gtLclVarCommon.gtLclNum; comp->lvaSetVarAddrExposed(lclNum); if (axc == AXC_AddrWide) { LclVarDsc* varDsc = &comp->lvaTable[lclNum]; if (varDsc->lvIsStructField) { comp->lvaSetVarAddrExposed(varDsc->lvParentLcl); } } // We may need to Quirk the storage size for this LCL_VAR // some PInvoke signatures incorrectly specify a ByRef to an INT32 // when they actually write a SIZE_T or INT64 if (axc == AXC_Addr) { comp->gtCheckQuirkAddrExposedLclVar(tree, fgWalkPre->parentStack); } } } // Push something to keep the PostCB, which will pop it, happy. axcStack->Push(AXC_None); // In the first case, tree may no longer be a leaf, but we're done with it; is a leaf in the second case. return WALK_SKIP_SUBTREES; case GT_ADD: assert(axc != AXC_Addr); // See below about treating pointer operations as wider indirection. if (tree->gtOp.gtOp1->gtType == TYP_BYREF || tree->gtOp.gtOp2->gtType == TYP_BYREF) { axcStack->Push(AXC_IndWide); } else if (axc == AXC_Ind) { // Let the children know that the parent was a GT_ADD, to be evaluated in an IND context. // If it's an add of a constant and an address, and the constant represents a field, // then we'll evaluate the address argument in an Ind context; otherwise, the None context. axcStack->Push(AXC_IndAdd); } else { axcStack->Push(axc); } return WALK_CONTINUE; // !!! Treat Pointer Operations as Wider Indirection // // If we are performing pointer operations, make sure we treat that as equivalent to a wider // indirection. This is because the pointers could be pointing to the address of struct fields // and could be used to perform operations on the whole struct or passed to another method. // // When visiting a node in this pre-order walk, we do not know if we would in the future // encounter a GT_ADDR of a GT_FIELD below. // // Note: GT_ADDR of a GT_FIELD is always a TYP_BYREF. // So let us be conservative and treat TYP_BYREF operations as AXC_IndWide and propagate a // wider indirection context down the expr tree. // // Example, in unsafe code, // // IL_000e 12 00 ldloca.s 0x0 // IL_0010 7c 02 00 00 04 ldflda 0x4000002 // IL_0015 12 00 ldloca.s 0x0 // IL_0017 7c 01 00 00 04 ldflda 0x4000001 // IL_001c 59 sub // // When visiting the GT_SUB node, if the types of either of the GT_SUB's operand are BYREF, then // consider GT_SUB to be equivalent of an AXC_IndWide. // // Similarly for pointer comparisons and pointer escaping as integers through conversions, treat // them as AXC_IndWide. // // BINOP case GT_SUB: case GT_MUL: case GT_DIV: case GT_UDIV: case GT_OR: case GT_XOR: case GT_AND: case GT_LSH: case GT_RSH: case GT_RSZ: case GT_ROL: case GT_ROR: case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GT: case GT_GE: // UNOP case GT_CAST: if ((tree->gtOp.gtOp1->gtType == TYP_BYREF) || (tree->OperIsBinary() && (tree->gtOp.gtOp2->gtType == TYP_BYREF))) { axcStack->Push(AXC_IndWide); return WALK_CONTINUE; } __fallthrough; default: // To be safe/conservative: pass Addr through, but not Ind -- otherwise, revert to "None". We must // handle the "Ind" propogation explicitly above. if (axc == AXC_Addr || axc == AXC_AddrWide) { axcStack->Push(axc); } else { axcStack->Push(AXC_None); } return WALK_CONTINUE; } } bool Compiler::fgFitsInOrNotLoc(GenTreePtr tree, unsigned width) { if (tree->TypeGet() != TYP_STRUCT) { return width <= genTypeSize(tree->TypeGet()); } else if (tree->OperGet() == GT_LCL_VAR) { assert(tree->TypeGet() == TYP_STRUCT); unsigned lclNum = tree->gtLclVarCommon.gtLclNum; return width <= lvaTable[lclNum].lvExactSize; } else if (tree->OperGet() == GT_FIELD) { CORINFO_CLASS_HANDLE fldClass = info.compCompHnd->getFieldClass (tree->gtField.gtFldHnd); return width <= info.compCompHnd->getClassSize(fldClass); } else { return false; } } void Compiler::fgAddFieldSeqForZeroOffset(GenTreePtr op1, FieldSeqNode* fieldSeq) { assert(op1->TypeGet() == TYP_BYREF || op1->TypeGet() == TYP_I_IMPL || op1->TypeGet() == TYP_REF); switch (op1->OperGet()) { case GT_ADDR: if (op1->gtOp.gtOp1->OperGet() == GT_LCL_FLD) { GenTreeLclFld* lclFld = op1->gtOp.gtOp1->AsLclFld(); lclFld->gtFieldSeq = GetFieldSeqStore()->Append(lclFld->gtFieldSeq, fieldSeq); } break; case GT_ADD: if (op1->gtOp.gtOp1->OperGet() == GT_CNS_INT) { FieldSeqNode* op1Fs = op1->gtOp.gtOp1->gtIntCon.gtFieldSeq; if (op1Fs != NULL) { op1Fs = GetFieldSeqStore()->Append(op1Fs, fieldSeq); op1->gtOp.gtOp1->gtIntCon.gtFieldSeq = op1Fs; } } else if (op1->gtOp.gtOp2->OperGet() == GT_CNS_INT) { FieldSeqNode* op2Fs = op1->gtOp.gtOp2->gtIntCon.gtFieldSeq; if (op2Fs != NULL) { op2Fs = GetFieldSeqStore()->Append(op2Fs, fieldSeq); op1->gtOp.gtOp2->gtIntCon.gtFieldSeq = op2Fs; } } break; case GT_CNS_INT: { FieldSeqNode* op1Fs = op1->gtIntCon.gtFieldSeq; if (op1Fs != NULL) { op1Fs = GetFieldSeqStore()->Append(op1Fs, fieldSeq); op1->gtIntCon.gtFieldSeq = op1Fs; } } break; default: // Record in the general zero-offset map. GetZeroOffsetFieldMap()->Set(op1, fieldSeq); break; } } /***************************************************************************** * * Mark address-taken locals. */ void Compiler::fgMarkAddressExposedLocals() { #ifdef DEBUG if (verbose) printf("\n*************** In fgMarkAddressExposedLocals()\n"); #endif // DEBUG BasicBlock* block = fgFirstBB; noway_assert(block); do { /* Make the current basic block address available globally */ compCurBB = block; GenTreePtr stmt; for (stmt = block->bbTreeList; stmt; stmt = stmt->gtNext) { // Call Compiler::fgMarkAddrTakenLocalsCB on each node AXCStack stk(this); stk.Push(AXC_None); // We start in neither an addr or ind context. fgWalkTree(&stmt->gtStmt.gtStmtExpr, fgMarkAddrTakenLocalsPreCB, fgMarkAddrTakenLocalsPostCB, &stk); } block = block->bbNext; } while (block); } // fgNodesMayInterfere: // return true if moving nodes relative to each other can change the result of a computation // // args: // read: a node which reads // bool Compiler::fgNodesMayInterfere(GenTree* write, GenTree* read) { LclVarDsc* srcVar = nullptr; bool srcAliased = false; bool dstAliased = false; bool readIsIndir = read->OperIsIndir() || read->OperIsImplicitIndir(); bool writeIsIndir = write->OperIsIndir() || write->OperIsImplicitIndir(); if (read->OperIsLocal()) srcVar = &lvaTable[read->gtLclVarCommon.gtLclNum]; if (writeIsIndir) { if (srcVar && srcVar->lvAddrExposed) return true; else if (readIsIndir) return true; return false; } else if (write->OperIsLocal()) { LclVarDsc* dstVar = &lvaTable[write->gtLclVarCommon.gtLclNum]; if (readIsIndir) { return dstVar->lvAddrExposed; } else if (read->OperIsLocal()) { if (read->gtLclVarCommon.gtLclNum == write->gtLclVarCommon.gtLclNum) return true; return false; } else { return false; } } else { return false; } } /** This predicate decides whether we will fold a tree with the structure: * x = x <op> y where x could be any arbitrary expression into * x <op>= y. * * This modification is only performed when the target architecture supports * complex addressing modes. In the case of ARM for example, this transformation * yields no benefit. * * In case this functions decides we can proceed to fold into an assignment operator * we need to inspect whether the operator is commutative to tell fgMorph whether we need to * reverse the tree due to the fact we saw x = y <op> x and we want to fold that into * x <op>= y because the operator property. */ bool Compiler::fgShouldCreateAssignOp(GenTreePtr tree, bool* bReverse) { #if CPU_LOAD_STORE_ARCH /* In the case of a load/store architecture, there's no gain by doing any of this, we bail. */ return false; #elif !defined(LEGACY_BACKEND) return false; #else // defined(LEGACY_BACKEND) GenTreePtr op1 = tree->gtOp.gtOp1; GenTreePtr op2 = tree->gtGetOp2(); genTreeOps cmop = op2->OperGet(); /* Is the destination identical to the first RHS sub-operand? */ if (GenTree::Compare(op1, op2->gtOp.gtOp1)) { /* Do not transform the following tree [0024CFA4] ----------- const int 1 [0024CFDC] ----G------ | int [0024CF5C] ----------- lclVar ubyte V01 tmp0 [0024D05C] -A--G------ = ubyte [0024D014] D------N--- lclVar ubyte V01 tmp0 to [0024CFA4] ----------- const int 1 [0024D05C] -A--G------ |= ubyte [0024D014] U------N--- lclVar ubyte V01 tmp0 , when V01 is a struct field local. */ if (op1->gtOper == GT_LCL_VAR && varTypeIsSmall(op1->TypeGet()) && op1->TypeGet() != op2->gtOp.gtOp2->TypeGet()) { unsigned lclNum = op1->gtLclVarCommon.gtLclNum; LclVarDsc* varDsc = lvaTable + lclNum; if (varDsc->lvIsStructField) { return false; } } *bReverse = false; return true; } else if (GenTree::OperIsCommutative(cmop)) { /* For commutative ops only, check for "a = x <op> a" */ /* Should we be doing this at all? */ if ((opts.compFlags & CLFLG_TREETRANS) == 0) { return false; } /* Can we swap the operands to cmop ... */ if ((op2->gtOp.gtOp1->gtFlags & GTF_ALL_EFFECT) && (op2->gtOp.gtOp2->gtFlags & GTF_ALL_EFFECT) ) { // Both sides must have side effects to prevent swap */ return false; } /* Is the destination identical to the second RHS sub-operand? */ if (GenTree::Compare(op1, op2->gtOp.gtOp2)) { *bReverse = true; return true; } } return false; #endif // defined(LEGACY_BACKEND) } // Static variables. Compiler::MorphAddrContext Compiler::s_CopyBlockMAC(Compiler::MACK_CopyBlock); #ifdef FEATURE_SIMD //----------------------------------------------------------------------------------- // fgMorphCombineSIMDFieldAssignments: // If the RHS of the input stmt is a read for simd vector X Field, then this function // will keep reading next few stmts based on the vector size(2, 3, 4). // If the next stmts LHS are located contiguous and RHS are also located // contiguous, then we replace those statements with a copyblk. // // Argument: // block - BasicBlock*. block which stmt belongs to // stmt - GenTreeStmt*. the stmt node we want to check // // return value: // if this funciton successfully optimized the stmts, then return true. Otherwise // return false; bool Compiler::fgMorphCombineSIMDFieldAssignments(BasicBlock* block, GenTreePtr stmt) { noway_assert(stmt->gtOper == GT_STMT); GenTreePtr tree = stmt->gtStmt.gtStmtExpr; assert(tree->OperGet() == GT_ASG); GenTreePtr originalLHS = tree->gtOp.gtOp1; GenTreePtr prevLHS = tree->gtOp.gtOp1; GenTreePtr prevRHS = tree->gtOp.gtOp2; unsigned index = 0; var_types baseType = TYP_UNKNOWN; unsigned simdSize = 0; GenTreePtr simdStructNode = getSIMDStructFromField(prevRHS, &baseType, &index, &simdSize, true); if (simdStructNode == nullptr || index != 0 || baseType != TYP_FLOAT) { // if the RHS is not from a SIMD vector field X, then there is no need to check further. return false; } int assignmentsCount = simdSize / genTypeSize(baseType) - 1; int remainingAssignments = assignmentsCount; GenTreePtr curStmt = stmt->gtNext; GenTreePtr lastStmt = stmt; while (curStmt != nullptr && remainingAssignments > 0) { GenTreePtr exp = curStmt->gtStmt.gtStmtExpr; if (exp->OperGet() != GT_ASG) { break; } GenTreePtr curLHS = exp->gtGetOp1(); GenTreePtr curRHS = exp->gtGetOp2(); if (!areArgumentsContiguous(prevLHS, curLHS) || !areArgumentsContiguous(prevRHS, curRHS)) { break; } remainingAssignments--; prevLHS = curLHS; prevRHS = curRHS; lastStmt = curStmt; curStmt = curStmt->gtNext; } if (remainingAssignments > 0) { // if the left assignments number is bigger than zero, then this means // that the assignments are not assgining to the contiguously memory // locations from same vector. return false; } #ifdef DEBUG if (verbose) { printf("\nFound contiguous assignments from a SIMD vector to memory.\n"); printf("From BB%02u, stmt", block->bbNum); printTreeID(stmt); printf(" to stmt"); printTreeID(lastStmt); printf("\n"); } #endif for (int i = 0; i < assignmentsCount; i++) { fgRemoveStmt(block, stmt->gtNext); } GenTree* copyBlkDst = createAddressNodeForSIMDInit(originalLHS, simdSize); if (simdStructNode->OperIsLocal()) { setLclRelatedToSIMDIntrinsic(simdStructNode); } GenTree* copyBlkAddr = copyBlkDst; if (copyBlkAddr->gtOper == GT_LEA) { copyBlkAddr = copyBlkAddr->AsAddrMode()->Base(); } GenTreeLclVarCommon* localDst = nullptr; if (copyBlkAddr->IsLocalAddrExpr(this, &localDst, nullptr)) { setLclRelatedToSIMDIntrinsic(localDst); } GenTree* simdStructAddr; if (simdStructNode->TypeGet() == TYP_BYREF) { assert(simdStructNode->OperIsLocal()); assert(lvaIsImplicitByRefLocal(simdStructNode->AsLclVarCommon()->gtLclNum)); simdStructAddr = simdStructNode; } else { assert(varTypeIsSIMD(simdStructNode)); simdStructAddr = gtNewOperNode(GT_ADDR, TYP_BYREF, simdStructNode); } #ifdef DEBUG if (verbose) { printf("\nBB%02u stmt", block->bbNum); printTreeID(stmt); printf("(before)\n"); gtDispTree(stmt); } #endif tree = gtNewBlkOpNode(GT_COPYBLK, copyBlkDst, simdStructAddr, gtNewIconNode(simdSize), false); stmt->gtStmt.gtStmtExpr = tree; // Since we generated a new address node which didn't exist before, // we should expose this address manually here. AXCStack stk(this); stk.Push(AXC_None); fgWalkTree(&stmt->gtStmt.gtStmtExpr, fgMarkAddrTakenLocalsPreCB, fgMarkAddrTakenLocalsPostCB, &stk); #ifdef DEBUG if (verbose) { printf("\nReplaced BB%02u stmt", block->bbNum); printTreeID(stmt); printf("(after)\n"); gtDispTree(stmt); } #endif return true; } #endif //FEATURE_SIMD
{ "content_hash": "a134f6f6e242c6b175ff9670bca093dc", "timestamp": "", "source": "github", "line_count": 16528, "max_line_length": 169, "avg_line_length": 36.99534123910939, "alnum_prop": 0.5275235134326259, "repo_name": "chuck-mitchell/coreclr", "id": "5be082dc98c0f84cda5574f4ce0e6816a19fb362", "size": "611459", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/jit/morph.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "946131" }, { "name": "Awk", "bytes": "5865" }, { "name": "Batchfile", "bytes": "64396" }, { "name": "C", "bytes": "6417414" }, { "name": "C#", "bytes": "134702950" }, { "name": "C++", "bytes": "68556720" }, { "name": "CMake", "bytes": "555143" }, { "name": "Groff", "bytes": "529523" }, { "name": "Groovy", "bytes": "63823" }, { "name": "HTML", "bytes": "16196" }, { "name": "Makefile", "bytes": "2527" }, { "name": "Objective-C", "bytes": "224031" }, { "name": "Perl", "bytes": "24550" }, { "name": "PowerShell", "bytes": "9231" }, { "name": "Python", "bytes": "69405" }, { "name": "Shell", "bytes": "77004" }, { "name": "Smalltalk", "bytes": "1359502" }, { "name": "SuperCollider", "bytes": "4752" }, { "name": "Yacc", "bytes": "157348" } ], "symlink_target": "" }
<?php namespace Braincrafted\BootstrapBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('braincrafted_bootstrap'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
{ "content_hash": "896738d52c781c0bdb797e10b27c2bfb", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 131, "avg_line_length": 31, "alnum_prop": 0.7230255839822024, "repo_name": "rukshan-rodrigo/demo-symfony", "id": "839f1484b2000b6d12e624c64a48aeb5fd1fdd37", "size": "899", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/braincrafted/bootstrap-bundle/Braincrafted/BootstrapBundle/DependencyInjection/Configuration.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package pl.edu.uj.JImageStream.tests.filters.color; import org.junit.Test; import pl.edu.uj.JImageStream.collectors.Collectors; import pl.edu.uj.JImageStream.filters.Filters; import pl.edu.uj.JImageStream.tests.AbstractBaseTest; import java.awt.image.BufferedImage; public class GrayScaleFilterTest extends AbstractBaseTest { @Test public void grayScaleFilterTest() { // tag::grayscaleFilter[] BufferedImage bufferedImage = streamableImage.stream() .apply(Filters.grayScaleFilter()) .collect(Collectors.toBufferedImage()); // end::grayscaleFilter[] save(streamableImage, bufferedImage, "GrayScaleFilter.png"); } }
{ "content_hash": "aa3176a15ddcb6b5f801e04a9720a91c", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 68, "avg_line_length": 31.59090909090909, "alnum_prop": 0.7194244604316546, "repo_name": "kmisztal/JImageStream", "id": "74d0bc5f23daa0e1f18d599806c0e550a334ceb7", "size": "695", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jis-documentation/src/test/java/pl/edu/uj/JImageStream/tests/filters/color/GrayScaleFilterTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "103903" } ], "symlink_target": "" }
SPEC_BEGIN(UAIAMUploadServerCertificateRequestSpec) describe(@"UAIAMUploadServerCertificateRequest", ^ { }); SPEC_END
{ "content_hash": "115d8c29cb53dc9974f28eb8a2d462ee", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 51, "avg_line_length": 12.2, "alnum_prop": 0.8032786885245902, "repo_name": "unsignedapps/ua-aws-sdk-ios", "id": "c2599042957ef5cc0ac4587341ac6b8082baf18c", "size": "406", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AWS iOS SDKTests/IAM/Requests/UAIAMUploadServerCertificateRequestTests.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "42359" }, { "name": "Objective-C", "bytes": "4812683" }, { "name": "Ruby", "bytes": "1520" } ], "symlink_target": "" }
/** */ package CIM15.IEC61970.Informative.InfAssetModels; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Winding Insulation Kind</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see CIM15.IEC61970.Informative.InfAssetModels.InfAssetModelsPackage#getWindingInsulationKind() * @generated */ public enum WindingInsulationKind implements Enumerator { /** * The '<em><b>Thermally Upgraded Paper</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #THERMALLY_UPGRADED_PAPER_VALUE * @generated * @ordered */ THERMALLY_UPGRADED_PAPER(0, "thermallyUpgradedPaper", "thermallyUpgradedPaper"), /** * The '<em><b>Other</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #OTHER_VALUE * @generated * @ordered */ OTHER(1, "other", "other"), /** * The '<em><b>Nomex</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #NOMEX_VALUE * @generated * @ordered */ NOMEX(2, "nomex", "nomex"), /** * The '<em><b>Paper</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #PAPER_VALUE * @generated * @ordered */ PAPER(3, "paper", "paper"); /** * The '<em><b>Thermally Upgraded Paper</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Thermally Upgraded Paper</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #THERMALLY_UPGRADED_PAPER * @generated * @ordered */ public static final int THERMALLY_UPGRADED_PAPER_VALUE = 0; /** * The '<em><b>Other</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Other</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #OTHER * @generated * @ordered */ public static final int OTHER_VALUE = 1; /** * The '<em><b>Nomex</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Nomex</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #NOMEX * @generated * @ordered */ public static final int NOMEX_VALUE = 2; /** * The '<em><b>Paper</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Paper</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #PAPER * @generated * @ordered */ public static final int PAPER_VALUE = 3; /** * An array of all the '<em><b>Winding Insulation Kind</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final WindingInsulationKind[] VALUES_ARRAY = new WindingInsulationKind[] { THERMALLY_UPGRADED_PAPER, OTHER, NOMEX, PAPER, }; /** * A public read-only list of all the '<em><b>Winding Insulation Kind</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<WindingInsulationKind> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Winding Insulation Kind</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static WindingInsulationKind get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { WindingInsulationKind result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Winding Insulation Kind</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static WindingInsulationKind getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { WindingInsulationKind result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Winding Insulation Kind</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static WindingInsulationKind get(int value) { switch (value) { case THERMALLY_UPGRADED_PAPER_VALUE: return THERMALLY_UPGRADED_PAPER; case OTHER_VALUE: return OTHER; case NOMEX_VALUE: return NOMEX; case PAPER_VALUE: return PAPER; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private WindingInsulationKind(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //WindingInsulationKind
{ "content_hash": "f7b40f3501a313148b74cb4f6d1e7bbb", "timestamp": "", "source": "github", "line_count": 257, "max_line_length": 116, "avg_line_length": 23.424124513618676, "alnum_prop": 0.6004983388704319, "repo_name": "SES-fortiss/SmartGridCoSimulation", "id": "f013812536176aa3cefc7a1bc06986f659b2705f", "size": "6020", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "core/cim15/src/CIM15/IEC61970/Informative/InfAssetModels/WindingInsulationKind.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "494" }, { "name": "C++", "bytes": "68972" }, { "name": "CSS", "bytes": "10495" }, { "name": "HTML", "bytes": "27854" }, { "name": "Java", "bytes": "23777284" }, { "name": "JavaScript", "bytes": "144441" }, { "name": "Processing", "bytes": "16761" }, { "name": "Shell", "bytes": "1069" }, { "name": "Solidity", "bytes": "18269" } ], "symlink_target": "" }
package org.rongji.dfish.misc.pinyin; class FindResult{ public FindResult(int state, int begin, int end) { this.state=state; this.begin=begin; this.end=end; } int begin; int end; int state; String replaceTo; static final int STATE_MATCH=1; static final int STATE_UNMATCH=0; static final int STATE_PREFIX=2; }
{ "content_hash": "d9fec5cc19352ec7ab2520dbb2192aad", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 51, "avg_line_length": 20.176470588235293, "alnum_prop": 0.6909620991253644, "repo_name": "rongji/pinyin", "id": "a0fb4eacf5e8b0bf2bb635538b7dbe766e40966f", "size": "343", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/rongji/dfish/misc/pinyin/FindResult.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "6732" } ], "symlink_target": "" }
package edu.kit.tm.pseprak2.alushare.network.coding; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.util.Random; import edu.kit.tm.pseprak2.alushare.BuildConfig; import static junit.framework.TestCase.assertEquals; /** * @author Albrecht Weiche */ @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21) public class CodingHelperTest { @Test public void testRandInt() { Random rn = new Random(); byte[] codedByte = new byte[4]; for (int n = 0; n < 100000; n++) { clearBuffer(codedByte); int startInt = rn.nextInt(); CodingHelper.intTo4Byte(startInt, codedByte); int resultInt = CodingHelper.intFromBuffer(codedByte); assertEquals("Coding changed integer! in pass: " + n, startInt, resultInt); } } @Test public void testRandLong() { Random rn = new Random(); byte[] codedByte = new byte[8]; for (int n = 0; n < 1000000; n++) { clearBuffer(codedByte); long startLong = rn.nextLong(); CodingHelper.longTo8Byte(startLong, codedByte); long resultLong = CodingHelper.longFromBuffer(codedByte); assertEquals("Coding changed long! in pass: " + n, startLong, resultLong); } } private void clearBuffer(byte[] buffer) { for (int index = 0; index < buffer.length; index++) { buffer[index] = 0; } } }
{ "content_hash": "c9b62a820c26749976f11a6eec14ce95", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 87, "avg_line_length": 26.672131147540984, "alnum_prop": 0.6318377381684082, "repo_name": "weichweich/AluShare", "id": "a099bf3055c231bd15c8f5980a0e5211a13fa004", "size": "1627", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/test/java/edu/kit/tm/pseprak2/alushare/network/coding/CodingHelperTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "783448" } ], "symlink_target": "" }
'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var Float64Array = require( '@stdlib/array/float64' ); var ArrayBuffer = require( '@stdlib/array/buffer' ); var pkg = require( './../package.json' ).name; var unshift = require( './../lib' ); // MAIN // bench( pkg+'::float64array,preallocated', function benchmark( b ) { var arr; var buf; var i; buf = new ArrayBuffer( b.iterations*8 ); // 8 bytes per double arr = new Float64Array( buf, b.iterations*8, 0 ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { arr = unshift( arr, i ); if ( arr.length !== i+1 ) { b.fail( 'should have added an element' ); } } b.toc(); if ( arr.length !== b.iterations ) { b.fail( 'should have added elements' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::float64array,preallocated,no-value', function benchmark( b ) { var arr; var buf; var i; buf = new ArrayBuffer( b.iterations*8 ); // 8 bytes per double arr = new Float64Array( buf, b.iterations*8, 0 ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { arr = unshift( arr ); if ( arr.length !== 0 ) { b.fail( 'should not have added an element' ); } } b.toc(); if ( arr.length !== 0 ) { b.fail( 'should not have added elements' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::float64array,preallocated,no-wrapper', function benchmark( b ) { var unshift; var arr; var buf; var i; unshift = require( './../lib/unshift_typed_array.js' ); buf = new ArrayBuffer( b.iterations*8 ); // 8 bytes per double arr = new Float64Array( buf, b.iterations*8, 0 ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { arr = unshift( arr, [ i ] ); if ( arr.length !== i+1 ) { b.fail( 'should have added an element' ); } } b.toc(); if ( arr.length !== b.iterations ) { b.fail( 'should have added elements' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::float64array,control,preallocated,constructor', function benchmark( b ) { var offset; var arr; var buf; var i; buf = new ArrayBuffer( b.iterations*8 ); // 8 bytes per double arr = new Float64Array( buf, b.iterations*8, 0 ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { // Here, we are only testing the operation of creating a new view each time a value must be added to a typed array: offset = arr.byteOffset - arr.BYTES_PER_ELEMENT; arr = new Float64Array( arr.buffer, offset, i+1 ); if ( arr.length !== i+1 ) { b.fail( 'should have added an element' ); } } b.toc(); if ( arr.length !== b.iterations ) { b.fail( 'should have added elements' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::float64array,control,preallocated,constructor,value', function benchmark( b ) { var offset; var arr; var buf; var i; var j; buf = new ArrayBuffer( b.iterations*8 ); // 8 bytes per double arr = new Float64Array( buf, b.iterations*8, 0 ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { offset = arr.byteOffset - arr.BYTES_PER_ELEMENT; arr = new Float64Array( arr.buffer, offset, i+1 ); for ( j = 0; j < 1; j++ ) { arr[ i+j ] = i + j; } if ( arr.length !== i+1 ) { b.fail( 'should have added an element' ); } } b.toc(); if ( arr.length !== b.iterations ) { b.fail( 'should have added elements' ); } b.pass( 'benchmark finished' ); b.end(); });
{ "content_hash": "e7b43ff2695173f67bd974de2ef04bf3", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 117, "avg_line_length": 23.680851063829788, "alnum_prop": 0.6049715483677748, "repo_name": "stdlib-js/stdlib", "id": "d41db8219d28fb13cb1b93ad51e1ec433ef12301", "size": "3955", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "lib/node_modules/@stdlib/utils/unshift/benchmark/benchmark.preallocation.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "21739" }, { "name": "C", "bytes": "15336495" }, { "name": "C++", "bytes": "1349482" }, { "name": "CSS", "bytes": "58039" }, { "name": "Fortran", "bytes": "198059" }, { "name": "HTML", "bytes": "56181" }, { "name": "Handlebars", "bytes": "16114" }, { "name": "JavaScript", "bytes": "85975525" }, { "name": "Julia", "bytes": "1508654" }, { "name": "Makefile", "bytes": "4806816" }, { "name": "Python", "bytes": "3343697" }, { "name": "R", "bytes": "576612" }, { "name": "Shell", "bytes": "559315" }, { "name": "TypeScript", "bytes": "19309407" }, { "name": "WebAssembly", "bytes": "5980" } ], "symlink_target": "" }
using Automatonymous; namespace GridDomain.Node.Actors.EventSourced.SnapshotsPolicy { public class OperationStateMachine<T> : AutomatonymousStateMachine<OperationState<T>> where T : class { public OperationStateMachine() { During(Initial, When(Start) .Then(c => c.Instance.Data = c.Data) .TransitionTo(Started)); During(Started, When(Fail) .Then(c => c.Instance.IsCompleted = true) .TransitionTo(Failed)); During(Started, When(Complete) .Then(c => c.Instance.IsCompleted = true) .TransitionTo(Completed)); } public Event<T> Start { get; private set; } public Event<T> Complete { get; private set; } public Event<T> Fail { get; private set; } public State Started { get; private set; } public State Completed { get; private set; } public State Failed { get; private set; } } }
{ "content_hash": "0cf74444214dae4edb3f93b35cecc2d6", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 106, "avg_line_length": 33.23529411764706, "alnum_prop": 0.5132743362831859, "repo_name": "linkelf/GridDomain", "id": "24cf8d4d5fb17692c276bae1a0add20e0c869338", "size": "1130", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "GridDomain.Node/Actors/EventSourced/SnapshotsPolicy/OperationStateMachine.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "195523" } ], "symlink_target": "" }
TODO: - read input file for Resources / Jobs - make Resources dynamic following a dedicated scenario - fix waiting for futures [OK] - simpleRunner does not work correctly with resource status - need to sync on resource.used attribute [OK] - when a Task is finished, it does to set resource as available [OK] - compile VS2013 [OK] - compile linux : g++ -o main main.cc -I./Scheduler -std=c++11 [FAILED] Very simple API for Simulator : - template parameter for JobRunner Strategy and Scheduler AssignementStrategy - call start method on the Scheduler instance
{ "content_hash": "865bb4b4e14348e6fd90dbca3f69dd6c", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 78, "avg_line_length": 40.785714285714285, "alnum_prop": 0.7513134851138353, "repo_name": "Bhaal22/mesos_test", "id": "9261e8869f60650ad6547188fe97635133c35820", "size": "585", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "5580" } ], "symlink_target": "" }
import {loadScript, checkData} from '../src/3p'; /** * @param {!Window} global * @param {!Object} data */ export function plista(global, data) { checkData(data, [ 'publickey', 'widgetname', 'urlprefix', 'item', 'geo', 'categories', 'countrycode' ]); const div = global.document.createElement('div'); div.setAttribute('data-display', 'plista_widget_' + data.widgetname); // container with id "c" is provided by amphtml global.document.getElementById('c').appendChild(div); window.PLISTA = { publickey: data.publickey, widgets: [{ name: data.widgetname, pre: data.urlprefix }], item: data.item, geo: data.geo, categories: data.categories, noCache: true, useDocumentReady: false, dataMode: 'data-display' }; // load the plista modules asynchronously loadScript(global, 'https://static' + (data.countrycode ? '-' + encodeURIComponent(data.countrycode) : '') + '.plista.com/async.js'); }
{ "content_hash": "13acf8b037ac8f9ab529640c9f4f5425", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 135, "avg_line_length": 28.41176470588235, "alnum_prop": 0.6521739130434783, "repo_name": "Meggin/amphtml", "id": "a23f27139e6cb6fa3354ca405b1673e45486ddc3", "size": "1593", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ads/plista.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "24745" }, { "name": "HTML", "bytes": "159117" }, { "name": "JavaScript", "bytes": "2124465" }, { "name": "Protocol Buffer", "bytes": "16354" }, { "name": "Python", "bytes": "25322" } ], "symlink_target": "" }
.class Landroid/view/accessibility/CaptioningManager$MyContentObserver; .super Landroid/database/ContentObserver; .source "CaptioningManager.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/view/accessibility/CaptioningManager; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x2 name = "MyContentObserver" .end annotation # instance fields .field private final mHandler:Landroid/os/Handler; .field final synthetic this$0:Landroid/view/accessibility/CaptioningManager; # direct methods .method public constructor <init>(Landroid/view/accessibility/CaptioningManager;Landroid/os/Handler;)V .locals 0 iput-object p1, p0, Landroid/view/accessibility/CaptioningManager$MyContentObserver;->this$0:Landroid/view/accessibility/CaptioningManager; invoke-direct {p0, p2}, Landroid/database/ContentObserver;-><init>(Landroid/os/Handler;)V iput-object p2, p0, Landroid/view/accessibility/CaptioningManager$MyContentObserver;->mHandler:Landroid/os/Handler; return-void .end method # virtual methods .method public onChange(ZLandroid/net/Uri;)V .locals 4 invoke-virtual {p2}, Landroid/net/Uri;->getPath()Ljava/lang/String; move-result-object v1 const/16 v2, 0x2f invoke-virtual {v1, v2}, Ljava/lang/String;->lastIndexOf(I)I move-result v2 add-int/lit8 v2, v2, 0x1 invoke-virtual {v1, v2}, Ljava/lang/String;->substring(I)Ljava/lang/String; move-result-object v0 const-string/jumbo v2, "accessibility_captioning_enabled" invoke-virtual {v2, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z move-result v2 if-eqz v2, :cond_0 iget-object v2, p0, Landroid/view/accessibility/CaptioningManager$MyContentObserver;->this$0:Landroid/view/accessibility/CaptioningManager; invoke-static {v2}, Landroid/view/accessibility/CaptioningManager;->-wrap0(Landroid/view/accessibility/CaptioningManager;)V :goto_0 return-void :cond_0 const-string/jumbo v2, "accessibility_captioning_locale" invoke-virtual {v2, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z move-result v2 if-eqz v2, :cond_1 iget-object v2, p0, Landroid/view/accessibility/CaptioningManager$MyContentObserver;->this$0:Landroid/view/accessibility/CaptioningManager; invoke-static {v2}, Landroid/view/accessibility/CaptioningManager;->-wrap2(Landroid/view/accessibility/CaptioningManager;)V goto :goto_0 :cond_1 const-string/jumbo v2, "accessibility_captioning_font_scale" invoke-virtual {v2, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z move-result v2 if-eqz v2, :cond_2 iget-object v2, p0, Landroid/view/accessibility/CaptioningManager$MyContentObserver;->this$0:Landroid/view/accessibility/CaptioningManager; invoke-static {v2}, Landroid/view/accessibility/CaptioningManager;->-wrap1(Landroid/view/accessibility/CaptioningManager;)V goto :goto_0 :cond_2 iget-object v2, p0, Landroid/view/accessibility/CaptioningManager$MyContentObserver;->mHandler:Landroid/os/Handler; iget-object v3, p0, Landroid/view/accessibility/CaptioningManager$MyContentObserver;->this$0:Landroid/view/accessibility/CaptioningManager; invoke-static {v3}, Landroid/view/accessibility/CaptioningManager;->-get0(Landroid/view/accessibility/CaptioningManager;)Ljava/lang/Runnable; move-result-object v3 invoke-virtual {v2, v3}, Landroid/os/Handler;->removeCallbacks(Ljava/lang/Runnable;)V iget-object v2, p0, Landroid/view/accessibility/CaptioningManager$MyContentObserver;->mHandler:Landroid/os/Handler; iget-object v3, p0, Landroid/view/accessibility/CaptioningManager$MyContentObserver;->this$0:Landroid/view/accessibility/CaptioningManager; invoke-static {v3}, Landroid/view/accessibility/CaptioningManager;->-get0(Landroid/view/accessibility/CaptioningManager;)Ljava/lang/Runnable; move-result-object v3 invoke-virtual {v2, v3}, Landroid/os/Handler;->post(Ljava/lang/Runnable;)Z goto :goto_0 .end method
{ "content_hash": "9bbfcaae99a9849e9c467a9df61e3459", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 145, "avg_line_length": 32.854838709677416, "alnum_prop": 0.7631320569464899, "repo_name": "BatMan-Rom/ModdedFiles", "id": "920ea1936a529073da481cd29d781578e147e362", "size": "4074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "framework.jar.out/smali_classes2/android/view/accessibility/CaptioningManager$MyContentObserver.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "15069" }, { "name": "HTML", "bytes": "139176" }, { "name": "Smali", "bytes": "541934400" } ], "symlink_target": "" }
#region Copyright //======================================================================================= // Microsoft Azure Customer Advisory Team // // This sample is supplemental to the technical guidance published on my personal // blog at http://blogs.msdn.com/b/paolos/. // // Author: Paolo Salvatori //======================================================================================= // Copyright (c) Microsoft Corporation. All rights reserved. // // LICENSED UNDER THE APACHE LICENSE, VERSION 2.0 (THE "LICENSE"); YOU MAY NOT USE THESE // FILES EXCEPT IN COMPLIANCE WITH THE LICENSE. YOU MAY OBTAIN A COPY OF THE LICENSE AT // http://www.apache.org/licenses/LICENSE-2.0 // UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, SOFTWARE DISTRIBUTED UNDER THE // LICENSE IS DISTRIBUTED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED. SEE THE LICENSE FOR THE SPECIFIC LANGUAGE GOVERNING // PERMISSIONS AND LIMITATIONS UNDER THE LICENSE. //======================================================================================= #endregion #region Using Directives using System; using FastColoredTextBoxNS; using Microsoft.ServiceBus.Messaging; using ServiceBusExplorer.Helpers; using ServiceBusExplorer.Forms; using ServiceBusExplorer.Utilities.Helpers; #endregion namespace ServiceBusExplorer.UIHelpers { public class LanguageDetector { #region Public Static Methods public static void SetFormattedMessage(ServiceBusHelper serviceBusHelper, BrokeredMessage message, FastColoredTextBox textBox) { if (serviceBusHelper == null) { throw new ArgumentNullException(nameof(serviceBusHelper), $"{nameof(serviceBusHelper)} parameter cannot be null"); } if (message == null) { throw new ArgumentNullException(nameof(message), $"{nameof(message)} parameter cannot be null"); } if (textBox == null) { throw new ArgumentNullException(nameof(textBox), $"{nameof(textBox)} parameter cannot be null"); } InternalSetFormattedMessage(serviceBusHelper.GetMessageText(message, MainForm.SingletonMainForm.UseAscii, out _), textBox); } public static void SetFormattedMessage(ServiceBusHelper serviceBusHelper, EventData message, FastColoredTextBox textBox) { if (serviceBusHelper == null) { throw new ArgumentNullException(nameof(serviceBusHelper), $"{nameof(serviceBusHelper)} parameter cannot be null"); } if (message == null) { throw new ArgumentNullException(nameof(message), $"{nameof(message)} parameter cannot be null"); } if (textBox == null) { throw new ArgumentNullException(nameof(textBox), $"{nameof(textBox)} parameter cannot be null"); } InternalSetFormattedMessage(serviceBusHelper.GetMessageText(message, out _), textBox); } public static void SetFormattedMessage(ServiceBusHelper serviceBusHelper, string messageText, FastColoredTextBox textBox) { if (serviceBusHelper == null) { throw new ArgumentNullException(nameof(serviceBusHelper), $"{nameof(serviceBusHelper)} parameter cannot be null"); } if (null == messageText) { throw new ArgumentNullException(nameof(messageText), $"{nameof(messageText)} parameter cannot be null"); } if (textBox == null) { throw new ArgumentNullException(nameof(textBox), $"{nameof(textBox)} parameter cannot be null"); } InternalSetFormattedMessage(messageText, textBox); } public static void SetFormattedMessage(string language, FastColoredTextBox textBox) { if (string.IsNullOrEmpty(language)) { throw new ArgumentNullException(nameof(language), $"{nameof(language)} parameter cannot be null"); } if (textBox == null) { throw new ArgumentNullException(nameof(textBox), $"{nameof(textBox)} parameter cannot be null"); } textBox.ClearStylesBuffer(); textBox.Range.ClearStyle(StyleIndex.All); switch (language) { case "JSON": textBox.Language = Language.JSON; break; case "XML": textBox.Language = Language.HTML; break; default: textBox.Language = Language.Custom; break; } textBox.OnTextChanged(); } #endregion #region Private Static Methods private static void InternalSetFormattedMessage(string message, FastColoredTextBox textBox) { if (JsonSerializerHelper.IsJson(message)) { textBox.Language = Language.JSON; textBox.Text = JsonSerializerHelper.Indent(message); } else if (XmlHelper.IsXml(message)) { textBox.Language = Language.HTML; textBox.Text = XmlHelper.Indent(message); } else { textBox.Language = Language.Custom; textBox.Text = string.IsNullOrEmpty(message) ? "" : message; } } #endregion } }
{ "content_hash": "8c6c4fce60d1cb57126a55f7f33fa555", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 134, "avg_line_length": 36.8051948051948, "alnum_prop": 0.5739237826393789, "repo_name": "paolosalvatori/ServiceBusExplorer", "id": "a341c7c8e5c5bde4df28252e8d9ad3e9746f84b5", "size": "5670", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/ServiceBusExplorer/UIHelpers/LanguageDetector.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3214447" }, { "name": "PowerShell", "bytes": "2664" }, { "name": "Smalltalk", "bytes": "49736" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <TITLE> CellFormat (POI API Documentation) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="CellFormat (POI API Documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/CellFormat.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/poi/ss/format/CellElapsedFormatter.html" title="class in org.apache.poi.ss.format"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/poi/ss/format/CellFormatCondition.html" title="class in org.apache.poi.ss.format"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/poi/ss/format/CellFormat.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CellFormat.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.apache.poi.ss.format</FONT> <BR> Class CellFormat</H2> <PRE> java.lang.Object <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.poi.ss.format.CellFormat</B> </PRE> <HR> <DL> <DT><PRE>public class <B>CellFormat</B><DT>extends java.lang.Object</DL> </PRE> <P> Format a value according to the standard Excel behavior. This "standard" is not explicitly documented by Microsoft, so the behavior is determined by experimentation; see the tests. <p> An Excel format has up to four parts, separated by semicolons. Each part specifies what to do with particular kinds of values, depending on the number of parts given: <dl> <dt>One part (example: <tt>[Green]#.##</tt>)</dt> <dd>If the value is a number, display according to this one part (example: green text, with up to two decimal points). If the value is text, display it as is.</dd> <dt>Two parts (example: <tt>[Green]#.##;[Red]#.##</tt>)</dt> <dd>If the value is a positive number or zero, display according to the first part (example: green text, with up to two decimal points); if it is a negative number, display according to the second part (example: red text, with up to two decimal points). If the value is text, display it as is.</dd> <dt>Three parts (example: <tt>[Green]#.##;[Black]#.##;[Red]#.##</tt>)</dt> <dd>If the value is a positive number, display according to the first part (example: green text, with up to two decimal points); if it is zero, display according to the second part (example: black text, with up to two decimal points); if it is a negative number, display according to the third part (example: red text, with up to two decimal points). If the value is text, display it as is.</dd> <dt>Four parts (example: <tt>[Green]#.##;[Black]#.##;[Red]#.##;[@]</tt>)</dt> <dd>If the value is a positive number, display according to the first part (example: green text, with up to two decimal points); if it is zero, display according to the second part (example: black text, with up to two decimal points); if it is a negative number, display according to the third part (example: red text, with up to two decimal points). If the value is text, display according to the fourth part (example: text in the cell's usual color, with the text value surround by brackets).</dd> </dl> <p> A given format part may specify a given Locale, by including something like <tt>[$$-409]</tt> or <tt>[$&pound;-809]</tt> or <tt>[$-40C]</tt>. These are (currently) largely ignored. You can use <A HREF="../../../../../org/apache/poi/ss/util/DateFormatConverter.html" title="class in org.apache.poi.ss.util"><CODE>DateFormatConverter</CODE></A> to look these up into Java Locales if desired. <p> In addition to these, there is a general format that is used when no format is specified. This formatting is presented by the <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#GENERAL_FORMAT"><CODE>GENERAL_FORMAT</CODE></A> object. TODO Merge this with <A HREF="../../../../../org/apache/poi/ss/usermodel/DataFormatter.html" title="class in org.apache.poi.ss.usermodel"><CODE>DataFormatter</CODE></A> so we only have one set of code for formatting numbers. TODO Re-use parts of this logic with <A HREF="../../../../../org/apache/poi/ss/usermodel/ConditionalFormatting.html" title="interface in org.apache.poi.ss.usermodel"><CODE>ConditionalFormatting</CODE></A> / <A HREF="../../../../../org/apache/poi/ss/usermodel/ConditionalFormattingRule.html" title="interface in org.apache.poi.ss.usermodel"><CODE>ConditionalFormattingRule</CODE></A> for reporting stylings which do/don't apply TODO Support the full set of modifiers, including alternate calendars and native character numbers, as documented at https://help.libreoffice.org/Common/Number_Format_Codes <P> <P> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format">CellFormat</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#GENERAL_FORMAT">GENERAL_FORMAT</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;<I>use <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#getInstance(java.util.Locale, java.lang.String)"><CODE>getInstance(Locale, String)</CODE></A> instead</I></TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format">CellFormatResult</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#apply(org.apache.poi.ss.usermodel.Cell)">apply</A></B>(<A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</A>&nbsp;c)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fetches the appropriate value from the cell, and returns the result of applying it to the appropriate format.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format">CellFormatResult</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#apply(javax.swing.JLabel, org.apache.poi.ss.usermodel.Cell)">apply</A></B>(javax.swing.JLabel&nbsp;label, <A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</A>&nbsp;c)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fetches the appropriate value from the cell, and uses the result, setting the text and color of a label before returning the result.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format">CellFormatResult</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#apply(javax.swing.JLabel, java.lang.Object)">apply</A></B>(javax.swing.JLabel&nbsp;label, java.lang.Object&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Uses the result of applying this format to the value, setting the text and color of a label before returning the result.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format">CellFormatResult</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#apply(java.lang.Object)">apply</A></B>(java.lang.Object&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the result of applying the format to the given value.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#equals(java.lang.Object)">equals</A></B>(java.lang.Object&nbsp;obj)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns <tt>true</tt> if the other object is a <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format"><CODE>CellFormat</CODE></A> object with the same format.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format">CellFormat</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#getInstance(java.util.Locale, java.lang.String)">getInstance</A></B>(java.util.Locale&nbsp;locale, java.lang.String&nbsp;format)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns a <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format"><CODE>CellFormat</CODE></A> that applies the given format.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format">CellFormat</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#getInstance(java.lang.String)">getInstance</A></B>(java.lang.String&nbsp;format)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns a <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format"><CODE>CellFormat</CODE></A> that applies the given format.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#hashCode()">hashCode</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns a hash code for the format.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#ultimateType(org.apache.poi.ss.usermodel.Cell)">ultimateType</A></B>(<A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</A>&nbsp;cell)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;<I>POI 3.15. This will return a CellType enum in the future</I></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../org/apache/poi/ss/usermodel/CellType.html" title="enum in org.apache.poi.ss.usermodel">CellType</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#ultimateTypeEnum(org.apache.poi.ss.usermodel.Cell)">ultimateTypeEnum</A></B>(<A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</A>&nbsp;cell)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;<I>POI 3.15 beta 3 Will be deleted when we make the CellType enum transition. See bug 59791.</I></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="GENERAL_FORMAT"><!-- --></A><H3> GENERAL_FORMAT</H3> <PRE> <FONT SIZE="-1">@Deprecated <A HREF="../../../../../org/apache/poi/util/Removal.html" title="annotation in org.apache.poi.util">@Removal</A>(<A HREF="../../../../../org/apache/poi/util/Removal.html#version()">version</A>="3.18") </FONT>public static final <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format">CellFormat</A> <B>GENERAL_FORMAT</B></PRE> <DL> <DD><B>Deprecated.</B>&nbsp;<I>use <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html#getInstance(java.util.Locale, java.lang.String)"><CODE>getInstance(Locale, String)</CODE></A> instead</I><DD>Format a value as it would be were no format specified. This is also used when the format specified is <tt>General</tt>. <P> <DL> </DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getInstance(java.lang.String)"><!-- --></A><H3> getInstance</H3> <PRE> public static <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format">CellFormat</A> <B>getInstance</B>(java.lang.String&nbsp;format)</PRE> <DL> <DD>Returns a <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format"><CODE>CellFormat</CODE></A> that applies the given format. Two calls with the same format may or may not return the same object. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>format</CODE> - The format. <DT><B>Returns:</B><DD>A <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format"><CODE>CellFormat</CODE></A> that applies the given format.</DL> </DD> </DL> <HR> <A NAME="getInstance(java.util.Locale, java.lang.String)"><!-- --></A><H3> getInstance</H3> <PRE> public static <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format">CellFormat</A> <B>getInstance</B>(java.util.Locale&nbsp;locale, java.lang.String&nbsp;format)</PRE> <DL> <DD>Returns a <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format"><CODE>CellFormat</CODE></A> that applies the given format. Two calls with the same format may or may not return the same object. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>locale</CODE> - The locale.<DD><CODE>format</CODE> - The format. <DT><B>Returns:</B><DD>A <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format"><CODE>CellFormat</CODE></A> that applies the given format.</DL> </DD> </DL> <HR> <A NAME="apply(java.lang.Object)"><!-- --></A><H3> apply</H3> <PRE> public <A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format">CellFormatResult</A> <B>apply</B>(java.lang.Object&nbsp;value)</PRE> <DL> <DD>Returns the result of applying the format to the given value. If the value is a number (a type of <CODE>Number</CODE> object), the correct number format type is chosen; otherwise it is considered a text object. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>value</CODE> - The value <DT><B>Returns:</B><DD>The result, in a <A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format"><CODE>CellFormatResult</CODE></A>.</DL> </DD> </DL> <HR> <A NAME="apply(org.apache.poi.ss.usermodel.Cell)"><!-- --></A><H3> apply</H3> <PRE> public <A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format">CellFormatResult</A> <B>apply</B>(<A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</A>&nbsp;c)</PRE> <DL> <DD>Fetches the appropriate value from the cell, and returns the result of applying it to the appropriate format. For formula cells, the computed value is what is used. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>c</CODE> - The cell. <DT><B>Returns:</B><DD>The result, in a <A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format"><CODE>CellFormatResult</CODE></A>.</DL> </DD> </DL> <HR> <A NAME="apply(javax.swing.JLabel, java.lang.Object)"><!-- --></A><H3> apply</H3> <PRE> public <A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format">CellFormatResult</A> <B>apply</B>(javax.swing.JLabel&nbsp;label, java.lang.Object&nbsp;value)</PRE> <DL> <DD>Uses the result of applying this format to the value, setting the text and color of a label before returning the result. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>label</CODE> - The label to apply to.<DD><CODE>value</CODE> - The value to process. <DT><B>Returns:</B><DD>The result, in a <A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format"><CODE>CellFormatResult</CODE></A>.</DL> </DD> </DL> <HR> <A NAME="apply(javax.swing.JLabel, org.apache.poi.ss.usermodel.Cell)"><!-- --></A><H3> apply</H3> <PRE> public <A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format">CellFormatResult</A> <B>apply</B>(javax.swing.JLabel&nbsp;label, <A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</A>&nbsp;c)</PRE> <DL> <DD>Fetches the appropriate value from the cell, and uses the result, setting the text and color of a label before returning the result. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>label</CODE> - The label to apply to.<DD><CODE>c</CODE> - The cell. <DT><B>Returns:</B><DD>The result, in a <A HREF="../../../../../org/apache/poi/ss/format/CellFormatResult.html" title="class in org.apache.poi.ss.format"><CODE>CellFormatResult</CODE></A>.</DL> </DD> </DL> <HR> <A NAME="ultimateType(org.apache.poi.ss.usermodel.Cell)"><!-- --></A><H3> ultimateType</H3> <PRE> public static int <B>ultimateType</B>(<A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</A>&nbsp;cell)</PRE> <DL> <DD><B>Deprecated.</B>&nbsp;<I>POI 3.15. This will return a CellType enum in the future</I> <P> <DD>Returns the ultimate cell type, following the results of formulas. If the cell is a <A HREF="../../../../../org/apache/poi/ss/usermodel/CellType.html#FORMULA"><CODE>CellType.FORMULA</CODE></A>, this returns the result of <A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html#getCachedFormulaResultTypeEnum()"><CODE>Cell.getCachedFormulaResultTypeEnum()</CODE></A>. Otherwise this returns the result of <A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html#getCellTypeEnum()"><CODE>Cell.getCellTypeEnum()</CODE></A>. Will return <A HREF="../../../../../org/apache/poi/ss/usermodel/CellType.html" title="enum in org.apache.poi.ss.usermodel"><CODE>CellType</CODE></A> in a future version of POI. For forwards compatibility, do not hard-code cell type literals in your code. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>cell</CODE> - The cell. <DT><B>Returns:</B><DD>The ultimate type of this cell.</DL> </DD> </DL> <HR> <A NAME="ultimateTypeEnum(org.apache.poi.ss.usermodel.Cell)"><!-- --></A><H3> ultimateTypeEnum</H3> <PRE> public static <A HREF="../../../../../org/apache/poi/ss/usermodel/CellType.html" title="enum in org.apache.poi.ss.usermodel">CellType</A> <B>ultimateTypeEnum</B>(<A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</A>&nbsp;cell)</PRE> <DL> <DD><B>Deprecated.</B>&nbsp;<I>POI 3.15 beta 3 Will be deleted when we make the CellType enum transition. See bug 59791.</I> <P> <DD>Returns the ultimate cell type, following the results of formulas. If the cell is a <A HREF="../../../../../org/apache/poi/ss/usermodel/CellType.html#FORMULA"><CODE>CellType.FORMULA</CODE></A>, this returns the result of <A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html#getCachedFormulaResultTypeEnum()"><CODE>Cell.getCachedFormulaResultTypeEnum()</CODE></A>. Otherwise this returns the result of <A HREF="../../../../../org/apache/poi/ss/usermodel/Cell.html#getCellTypeEnum()"><CODE>Cell.getCellTypeEnum()</CODE></A>. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>cell</CODE> - The cell. <DT><B>Returns:</B><DD>The ultimate type of this cell.<DT><B>Since:</B></DT> <DD>POI 3.15 beta 3</DD> </DL> </DD> </DL> <HR> <A NAME="equals(java.lang.Object)"><!-- --></A><H3> equals</H3> <PRE> public boolean <B>equals</B>(java.lang.Object&nbsp;obj)</PRE> <DL> <DD>Returns <tt>true</tt> if the other object is a <A HREF="../../../../../org/apache/poi/ss/format/CellFormat.html" title="class in org.apache.poi.ss.format"><CODE>CellFormat</CODE></A> object with the same format. <P> <DD><DL> <DT><B>Overrides:</B><DD><CODE>equals</CODE> in class <CODE>java.lang.Object</CODE></DL> </DD> <DD><DL> <DT><B>Parameters:</B><DD><CODE>obj</CODE> - The other object. <DT><B>Returns:</B><DD><tt>true</tt> if the two objects are equal.</DL> </DD> </DL> <HR> <A NAME="hashCode()"><!-- --></A><H3> hashCode</H3> <PRE> public int <B>hashCode</B>()</PRE> <DL> <DD>Returns a hash code for the format. <P> <DD><DL> <DT><B>Overrides:</B><DD><CODE>hashCode</CODE> in class <CODE>java.lang.Object</CODE></DL> </DD> <DD><DL> <DT><B>Returns:</B><DD>A hash code for the format.</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/CellFormat.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/poi/ss/format/CellElapsedFormatter.html" title="class in org.apache.poi.ss.format"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/poi/ss/format/CellFormatCondition.html" title="class in org.apache.poi.ss.format"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/poi/ss/format/CellFormat.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CellFormat.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright 2017 The Apache Software Foundation or its licensors, as applicable.</i> </BODY> </HTML>
{ "content_hash": "0a3ac7987c3980c5aa2b84c1d2fc49df", "timestamp": "", "source": "github", "line_count": 558, "max_line_length": 299, "avg_line_length": 52.155913978494624, "alnum_prop": 0.6541250042950899, "repo_name": "wzul/237767", "id": "8fcb3439a5e795e2f4ac4179237744bd51cc0e9b", "size": "29103", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Assignment_2 (OLD)/Assignment2/build/classes/ApachePOI/docs/apidocs/org/apache/poi/ss/format/CellFormat.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31414" }, { "name": "HTML", "bytes": "209051376" }, { "name": "Java", "bytes": "62613" } ], "symlink_target": "" }
set(DOCUMENTATION "This module constains classes related to the visualization of the level-sets.") itk_module( ITKLevelSetsv4Visualization DEPENDS ITKLevelSetsv4 ITKVtkGlue TEST_DEPENDS ITKTestKernel EXCLUDE_FROM_DEFAULT DESCRIPTION "${DOCUMENTATION}" )
{ "content_hash": "38bc60d5bb576cdc1e85e78233b12018", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 63, "avg_line_length": 22.692307692307693, "alnum_prop": 0.7254237288135593, "repo_name": "RayRuizhiLiao/ITK_4D", "id": "457f6c91374f20ddfd3543e101aaacbbdf0434a6", "size": "295", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Modules/Segmentation/LevelSetsv4Visualization/itk-module.cmake", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "572693" }, { "name": "C++", "bytes": "36720665" }, { "name": "CMake", "bytes": "1448020" }, { "name": "CSS", "bytes": "18346" }, { "name": "Java", "bytes": "29480" }, { "name": "Objective-C++", "bytes": "6753" }, { "name": "Perl", "bytes": "6113" }, { "name": "Python", "bytes": "385395" }, { "name": "Ruby", "bytes": "309" }, { "name": "Shell", "bytes": "92050" }, { "name": "Tcl", "bytes": "75202" }, { "name": "XSLT", "bytes": "8874" } ], "symlink_target": "" }
import React from 'react'; import { mount } from 'enzyme'; import Modal from '../../../components/modal/modal'; describe('Modal: componentWillUnmount', () => { const removeEventListener = global.window.document.removeEventListener; beforeEach(() => { global.window.document.removeEventListener = jest.fn(); }); afterEach(() => { global.window.document.removeEventListener = removeEventListener; }); it('should remove "keydown" listener before unmount', () => { const wrapper = mount( <Modal> Modal Content </Modal> ); wrapper.unmount(); expect(global.window.document.removeEventListener).toBeCalled(); }); it('should remove "keydown" listener before unmount', () => { const wrapper = mount( <Modal closeOnEsc={false} > Modal Content </Modal> ); wrapper.unmount(); expect(global.window.document.removeEventListener).not.toBeCalled(); }); });
{ "content_hash": "3b576a841c13955d46036a6b77b0bba2", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 73, "avg_line_length": 25.89189189189189, "alnum_prop": 0.6388308977035491, "repo_name": "Travix-International/travix-ui-kit", "id": "b2844292c9f01f8f77022be7a10abf0403868d01", "size": "958", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/unit/modal/modal.componentWillUnmount.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "68863" }, { "name": "HTML", "bytes": "1259" }, { "name": "JavaScript", "bytes": "395750" }, { "name": "Makefile", "bytes": "1569" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Cake. // </auto-generated> //------------------------------------------------------------------------------ using System.Reflection; [assembly: AssemblyProduct("Cake")] [assembly: AssemblyVersion("0.6.0")] [assembly: AssemblyFileVersion("0.6.0")] [assembly: AssemblyInformationalVersion("0.6.0")] [assembly: AssemblyCopyright("Copyright (c) Patrik Svensson, Mattias Karlsson and contributors")]
{ "content_hash": "85a0472f0c410b0f11362740e94476f8", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 97, "avg_line_length": 41, "alnum_prop": 0.5140712945590994, "repo_name": "yvschmid/cake", "id": "2d82ccf1c38f37b65ea31c26bc5c870f3683f72f", "size": "535", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/SolutionInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2692289" }, { "name": "PowerShell", "bytes": "1772" }, { "name": "Shell", "bytes": "2240" } ], "symlink_target": "" }
Kita menggunakan [Scrapy](https://doc.scrapy.org) untuk dasar `rojak-pantau`. Hal ini dikarenakan beberapa pertimbangan yang telah kita diskusikan antara lain: 1. Cocok untuk tim. Setiap anggota tim yang mau menambah media tinggal melakukan penambahan dan perubahan sedikit pada source code. 2. Mudah di deploy 3. Lengkapnya dokumentasi ## Setup Pastikan kamu sudah mensetup instance MySQL lokal lalu mempopulate database nya: cd rojak-database python insert_candidate_data.py python insert_media_data.py ## Jalanin pemantau sh install_dependencies.sh scrapy crawl detikcom # untuk jalanin rojak-pantau-detik ## Cara penambahan media baru Untuk penambahan media baru tinggal copy file `rojak_pantau/spider/detikcom.py` lalu mengubah nama file dan class sesuai nama media. Lalu tinggal memodifikasi `name`, `start_urls`, method `parse` dan method `parse_news` ## Catatan untuk untuk membuat spider baru * `raw_content` harus berisi raw HTML bukan raw plain text. Karena ini kita gunakan untuk proses selanjutnya. (Contoh: extract first paragraph) ## Resources * [Scrapy 1.2 documentation](https://doc.scrapy.org/en/latest/index.html)
{ "content_hash": "c1563d0bd532e5fe543be02b92872da5", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 80, "avg_line_length": 29.974358974358974, "alnum_prop": 0.7758768177929855, "repo_name": "bobbypriambodo/rojak", "id": "b15b34280d369cfb4c57b442fd74cf5214de7dbb", "size": "1185", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "rojak-pantau/README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2303" }, { "name": "Elixir", "bytes": "74193" }, { "name": "HTML", "bytes": "889" }, { "name": "Java", "bytes": "20877" }, { "name": "JavaScript", "bytes": "31166" }, { "name": "Python", "bytes": "204215" }, { "name": "Ruby", "bytes": "927" }, { "name": "Shell", "bytes": "2094" }, { "name": "Swift", "bytes": "5899" } ], "symlink_target": "" }
package org.elasticsearch.index.query; import org.apache.lucene.search.Filter; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.HashedBytesRef; import org.elasticsearch.common.lucene.search.NotFilter; import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; /** * */ public class NotFilterParser implements FilterParser { public static final String NAME = "not"; @Inject public NotFilterParser() { } @Override public String[] names() { return new String[]{NAME}; } @Override public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); Filter filter = null; boolean filterFound = false; boolean cache = false; HashedBytesRef cacheKey = null; String filterName = null; String currentFieldName = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { if ("filter".equals(currentFieldName)) { filter = parseContext.parseInnerFilter(); filterFound = true; } else { filterFound = true; // its the filter, and the name is the field filter = parseContext.parseInnerFilter(currentFieldName); } } else if (token == XContentParser.Token.START_ARRAY) { filterFound = true; // its the filter, and the name is the field filter = parseContext.parseInnerFilter(currentFieldName); } else if (token.isValue()) { if ("_cache".equals(currentFieldName)) { cache = parser.booleanValue(); } else if ("_name".equals(currentFieldName)) { filterName = parser.text(); } else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) { cacheKey = new HashedBytesRef(parser.text()); } else { throw new QueryParsingException(parseContext.index(), "[not] filter does not support [" + currentFieldName + "]"); } } } if (!filterFound) { throw new QueryParsingException(parseContext.index(), "filter is required when using `not` filter"); } if (filter == null) { return null; } Filter notFilter = new NotFilter(filter); if (cache) { notFilter = parseContext.cacheFilter(notFilter, cacheKey, parseContext.autoFilterCachePolicy()); } if (filterName != null) { parseContext.addNamedFilter(filterName, notFilter); } return notFilter; } }
{ "content_hash": "9531aed29f0a8a4e2685dfbc9cc30a6b", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 134, "avg_line_length": 35.3448275862069, "alnum_prop": 0.5889430894308944, "repo_name": "kkirsche/elasticsearch", "id": "3eb94b99d6248292624559d161fc059a64bbab16", "size": "3863", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "src/main/java/org/elasticsearch/index/query/NotFilterParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "87" }, { "name": "Groovy", "bytes": "299" }, { "name": "HTML", "bytes": "1210" }, { "name": "Java", "bytes": "26518391" }, { "name": "Perl", "bytes": "6858" }, { "name": "Python", "bytes": "64868" }, { "name": "Ruby", "bytes": "17776" }, { "name": "Shell", "bytes": "35009" } ], "symlink_target": "" }
using System; using osu.Framework.Input.Events; namespace osu.Game.Screens.Edit.Compose.Components { public abstract class SelectionBoxDragHandle : SelectionBoxControl { public Action<DragEvent> HandleDrag { get; set; } protected override bool OnDragStart(DragStartEvent e) { TriggerOperationStarted(); return true; } protected override void OnDrag(DragEvent e) { HandleDrag?.Invoke(e); base.OnDrag(e); } protected override void OnDragEnd(DragEndEvent e) { TriggerOperatoinEnded(); UpdateHoverState(); base.OnDragEnd(e); } #region Internal events for SelectionBoxDragHandleContainer internal event Action HoverGained; internal event Action HoverLost; internal event Action MouseDown; internal event Action MouseUp; protected override bool OnHover(HoverEvent e) { bool result = base.OnHover(e); HoverGained?.Invoke(); return result; } protected override void OnHoverLost(HoverLostEvent e) { base.OnHoverLost(e); HoverLost?.Invoke(); } protected override bool OnMouseDown(MouseDownEvent e) { bool result = base.OnMouseDown(e); MouseDown?.Invoke(); return result; } protected override void OnMouseUp(MouseUpEvent e) { base.OnMouseUp(e); MouseUp?.Invoke(); } #endregion } }
{ "content_hash": "cdda60c1fb86e60e052a382b1a5014ad", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 70, "avg_line_length": 24.953846153846154, "alnum_prop": 0.5745992601726264, "repo_name": "smoogipooo/osu", "id": "65a95951cf6b081ed0d5a23d46715dede1e60205", "size": "1772", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "osu.Game/Screens/Edit/Compose/Components/SelectionBoxDragHandle.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1322865" } ], "symlink_target": "" }
#include "rtc_tools/network_tester/packet_sender.h" #include <algorithm> #include <string> #include <utility> #include "rtc_base/timeutils.h" #include "rtc_tools/network_tester/config_reader.h" #include "rtc_tools/network_tester/test_controller.h" namespace webrtc { namespace { class SendPacketTask : public rtc::QueuedTask { public: explicit SendPacketTask(PacketSender* packet_sender) : target_time_ms_(rtc::TimeMillis()), packet_sender_(packet_sender) {} private: bool Run() override { if (packet_sender_->IsSending()) { packet_sender_->SendPacket(); target_time_ms_ += packet_sender_->GetSendIntervalMs(); int64_t delay_ms = std::max(static_cast<int64_t>(0), target_time_ms_ - rtc::TimeMillis()); rtc::TaskQueue::Current()->PostDelayedTask( std::unique_ptr<QueuedTask>(this), delay_ms); return false; } else { return true; } } int64_t target_time_ms_; PacketSender* const packet_sender_; }; class UpdateTestSettingTask : public rtc::QueuedTask { public: UpdateTestSettingTask(PacketSender* packet_sender, std::unique_ptr<ConfigReader> config_reader) : packet_sender_(packet_sender), config_reader_(std::move(config_reader)) {} private: bool Run() override { auto config = config_reader_->GetNextConfig(); if (config) { packet_sender_->UpdateTestSetting((*config).packet_size, (*config).packet_send_interval_ms); rtc::TaskQueue::Current()->PostDelayedTask( std::unique_ptr<QueuedTask>(this), (*config).execution_time_ms); return false; } else { packet_sender_->StopSending(); return true; } } PacketSender* const packet_sender_; const std::unique_ptr<ConfigReader> config_reader_; }; } // namespace PacketSender::PacketSender(TestController* test_controller, const std::string& config_file_path) : packet_size_(0), send_interval_ms_(0), sequence_number_(0), sending_(false), config_file_path_(config_file_path), test_controller_(test_controller), worker_queue_("Packet Sender", rtc::TaskQueue::Priority::HIGH) {} PacketSender::~PacketSender() = default; void PacketSender::StartSending() { worker_queue_checker_.Detach(); worker_queue_.PostTask([this]() { RTC_DCHECK_CALLED_SEQUENTIALLY(&worker_queue_checker_); sending_ = true; }); worker_queue_.PostTask( std::unique_ptr<rtc::QueuedTask>(new UpdateTestSettingTask( this, std::unique_ptr<ConfigReader>(new ConfigReader(config_file_path_))))); worker_queue_.PostTask( std::unique_ptr<rtc::QueuedTask>(new SendPacketTask(this))); } void PacketSender::StopSending() { RTC_DCHECK_CALLED_SEQUENTIALLY(&worker_queue_checker_); sending_ = false; test_controller_->OnTestDone(); } bool PacketSender::IsSending() const { RTC_DCHECK_CALLED_SEQUENTIALLY(&worker_queue_checker_); return sending_; } void PacketSender::SendPacket() { RTC_DCHECK_CALLED_SEQUENTIALLY(&worker_queue_checker_); NetworkTesterPacket packet; packet.set_type(NetworkTesterPacket::TEST_DATA); packet.set_sequence_number(sequence_number_++); packet.set_send_timestamp(rtc::TimeMicros()); test_controller_->SendData(packet, packet_size_); } int64_t PacketSender::GetSendIntervalMs() const { RTC_DCHECK_CALLED_SEQUENTIALLY(&worker_queue_checker_); return send_interval_ms_; } void PacketSender::UpdateTestSetting(size_t packet_size, int64_t send_interval_ms) { RTC_DCHECK_CALLED_SEQUENTIALLY(&worker_queue_checker_); send_interval_ms_ = send_interval_ms; packet_size_ = packet_size; } } // namespace webrtc
{ "content_hash": "314ddadcc534f8e61737806c986f78b3", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 80, "avg_line_length": 30.272, "alnum_prop": 0.6619978858350951, "repo_name": "wangcy6/storm_app", "id": "2c38b2fc4de3a94a638a8b0484baa5cfb5f585fc", "size": "4192", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frame/c++/webrtc-master/rtc_tools/network_tester/packet_sender.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "86225" }, { "name": "Assembly", "bytes": "4834" }, { "name": "Batchfile", "bytes": "50141" }, { "name": "C", "bytes": "9700081" }, { "name": "C#", "bytes": "1587148" }, { "name": "C++", "bytes": "14378340" }, { "name": "CMake", "bytes": "756439" }, { "name": "CSS", "bytes": "59712" }, { "name": "Clojure", "bytes": "535480" }, { "name": "DTrace", "bytes": "147" }, { "name": "Fancy", "bytes": "6234" }, { "name": "FreeMarker", "bytes": "3512" }, { "name": "Go", "bytes": "27069" }, { "name": "Groovy", "bytes": "1755" }, { "name": "HTML", "bytes": "1235479" }, { "name": "Java", "bytes": "41653938" }, { "name": "JavaScript", "bytes": "260093" }, { "name": "Lua", "bytes": "11887" }, { "name": "M4", "bytes": "96283" }, { "name": "Makefile", "bytes": "977879" }, { "name": "NSIS", "bytes": "6522" }, { "name": "Objective-C", "bytes": "324010" }, { "name": "PHP", "bytes": "348909" }, { "name": "Perl", "bytes": "182487" }, { "name": "PowerShell", "bytes": "19465" }, { "name": "Prolog", "bytes": "243" }, { "name": "Python", "bytes": "3649738" }, { "name": "QML", "bytes": "9975" }, { "name": "QMake", "bytes": "63106" }, { "name": "Roff", "bytes": "12319" }, { "name": "Ruby", "bytes": "858066" }, { "name": "Scala", "bytes": "5203874" }, { "name": "Shell", "bytes": "714435" }, { "name": "Smarty", "bytes": "1047" }, { "name": "Swift", "bytes": "3486" }, { "name": "Tcl", "bytes": "492616" }, { "name": "Thrift", "bytes": "31449" }, { "name": "XS", "bytes": "20183" }, { "name": "XSLT", "bytes": "8784" } ], "symlink_target": "" }
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: The first node of linked list. * @return: The node where the cycle begins. * if there is no cycle, return null */ ListNode *detectCycle(ListNode *head) { // write your code here if (NULL == head || NULL == head->next) { return NULL; } ListNode *slow = head; ListNode *fast = head; while (slow && fast && fast->next) { slow = slow->next; fast = fast->next->next; if (fast == slow) { break; } } slow = head; while (slow && fast && slow != fast) { slow = slow->next; fast = fast->next; } return fast; } };
{ "content_hash": "a4c0640071c8eeb869ebb215db83b0ff", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 50, "avg_line_length": 23.902439024390244, "alnum_prop": 0.45102040816326533, "repo_name": "FeiZhan/Algo-Collection", "id": "b61d47d5139bd43db665a5a8492687e66fa90d53", "size": "980", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "answers/lintcode/Linked List Cycle II.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "892410" }, { "name": "Java", "bytes": "743448" }, { "name": "JavaScript", "bytes": "3093" }, { "name": "Python", "bytes": "93383" }, { "name": "Shell", "bytes": "891" } ], "symlink_target": "" }
import type {FramebufferProps, ColorAttachment} from '@luma.gl/api'; import {Device, log, assert} from '@luma.gl/api'; import GL from '@luma.gl/constants'; import {getWebGL2Context, assertWebGL2Context} from '@luma.gl/webgl'; import {getKey} from '../webgl-utils/constants-to-keys'; import Renderbuffer from './renderbuffer'; import {clear, clearBuffer} from './clear'; import Texture from './texture'; // import {copyToDataUrl} from './copy-and-blit'; import {WebGLDevice, WEBGLFramebuffer} from '@luma.gl/webgl'; export type TextureAttachment = [Texture, number?, number?]; export type Attachment = WebGLTexture | Renderbuffer | TextureAttachment; const ERR_MULTIPLE_RENDERTARGETS = 'Multiple render targets not supported'; /** @deprecated backwards compatibility props */ export type ClassicFramebufferProps = FramebufferProps & { attachments?: Record<number, Attachment | Renderbuffer>; readBuffer?: number; drawBuffers?: number[]; check?: boolean; width?: number; height?: number; color?: boolean; depth?: boolean; stencil?: boolean; }; type ColorBufferFloatOptions = {colorBufferFloat?: boolean; colorBufferHalfFloat?: boolean}; /** Convert classic framebuffer attachments array to WebGPU style attachments */ function getDefaultProps(props: ClassicFramebufferProps): FramebufferProps { const newProps: FramebufferProps = {...props}; const {color = true, depth = true, stencil = false} = props; if (props.attachments) { newProps.depthStencilAttachment = undefined; newProps.colorAttachments = newProps.colorAttachments || []; for (const [attachmentPoint, attachment] of Object.entries(props.attachments)) { switch (Number(attachmentPoint) as GL) { case GL.DEPTH_ATTACHMENT: case GL.STENCIL_ATTACHMENT: case GL.DEPTH_STENCIL_ATTACHMENT: // @ts-expect-error newProps.depthStencilAttachment = attachment; break; default: // TODO, map attachmentPoint // @ts-expect-error newProps.colorAttachments.push(attachment); break; } } // @ts-expect-error delete newProps.attachments; return newProps; } if (color) { newProps.colorAttachments = newProps.colorAttachments || ['rgba8unorm-unsized']; } if (depth && stencil) { newProps.depthStencilAttachment = newProps.depthStencilAttachment || 'depth24plus-stencil8'; } else if (depth) { newProps.depthStencilAttachment = newProps.depthStencilAttachment || 'depth16unorm'; } else if (stencil) { newProps.depthStencilAttachment = newProps.depthStencilAttachment || 'stencil8'; } return newProps; } /** @deprecated Use device.createFramebuffer() */ export default class ClassicFramebuffer extends WEBGLFramebuffer { width = null; height = null; attachments = {}; readBuffer = GL.COLOR_ATTACHMENT0; drawBuffers = [GL.COLOR_ATTACHMENT0]; ownResources = []; static readonly FRAMEBUFFER_ATTACHMENT_PARAMETERS = [ GL.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, // WebGLRenderbuffer or WebGLTexture GL.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, // GL.RENDERBUFFER, GL.TEXTURE, GL.NONE // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, // GL.TEXTURE_CUBE_MAP_POSITIVE_X, etc. // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, // GLint // EXT_sRGB or WebGL2 GL.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, // GL.LINEAR, GL.SRBG // WebGL2 // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, // GLint GL.FRAMEBUFFER_ATTACHMENT_RED_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE // GLint // GL.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE // GL.FLOAT, GL.INT, GL.UNSIGNED_INT, GL.SIGNED_NORMALIZED, OR GL.UNSIGNED_NORMALIZED. ]; /** * Check color buffer float support * @param options.colorBufferFloat Whether floating point textures can be rendered and read * @param options.colorBufferHalfFloat Whether half float textures can be rendered and read */ static isSupported(gl: WebGLRenderingContext, options: ColorBufferFloatOptions): boolean { return isFloatColorBufferSupported(gl, options); } /** * returns the default Classic * Creates a Framebuffer object wrapper for the default WebGL framebuffer (target === null) */ static getDefaultFramebuffer(gl: WebGLRenderingContext): ClassicFramebuffer { const webglDevice = WebGLDevice.attach(gl); // @ts-expect-error webglDevice.defaultFramebuffer = // @ts-expect-error webglDevice.defaultFramebuffer || new ClassicFramebuffer(gl, { id: 'default-framebuffer', handle: null, attachments: {}, check: false }); // TODO - can we query for and get a handle to the GL.FRONT renderbuffer? // @ts-expect-error return webglDevice.defaultFramebuffer; } get MAX_COLOR_ATTACHMENTS(): number { const gl2 = assertWebGL2Context(this.gl); return gl2.getParameter(gl2.MAX_COLOR_ATTACHMENTS); } get MAX_DRAW_BUFFERS(): number { const gl2 = assertWebGL2Context(this.gl); return gl2.getParameter(gl2.MAX_DRAW_BUFFERS); } constructor(gl: Device | WebGLRenderingContext, props: ClassicFramebufferProps = {}) { super(WebGLDevice.attach(gl), getDefaultProps(props)); this.initialize(props); Object.seal(this); } get color() { return this.colorAttachments[0] || null; // return this.attachments[GL.COLOR_ATTACHMENT0] || null; } get texture() { return this.colorAttachments[0] || null; // return this.attachments[GL.COLOR_ATTACHMENT0] || null; } get depth() { return ( this.depthStencilAttachment || null // this.attachments[GL.DEPTH_ATTACHMENT] || this.attachments[GL.DEPTH_STENCIL_ATTACHMENT] || null ); } get stencil() { return ( this.depthStencilAttachment || // this.attachments[GL.STENCIL_ATTACHMENT] || // this.attachments[GL.DEPTH_STENCIL_ATTACHMENT] || null ); } // initialize(props?: ClassicFramebufferProps): this; initialize(props: ClassicFramebufferProps) { let {attachments = null} = props || {}; const { width = 1, height = 1, check = true, readBuffer = undefined, drawBuffers = undefined } = props || {}; assert(width >= 0 && height >= 0, 'Width and height need to be integers'); // Store actual width and height for diffing this.width = width; this.height = height; // Resize any provided attachments - note that resize only resizes if needed // Note: A framebuffer has no separate size, it is defined by its attachments (which must agree) if (attachments) { for (const attachment in attachments) { const target = attachments[attachment]; const object = Array.isArray(target) ? target[0] : target; // @ts-expect-error object.resize({width, height}); } } else { // Create any requested default attachments // attachments = this._createDefaultAttachments(color, depth, stencil, width, height); } this.update({clearAttachments: true, attachments, readBuffer, drawBuffers}); // Checks that framebuffer was properly set up, if not, throws an explanatory error if (attachments && check) { this.checkStatus(); } } checkStatus(): this { super._checkStatus(); return this; } getStatus(): number { const {gl} = this; const prevHandle = gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); const status = gl.checkFramebufferStatus(GL.FRAMEBUFFER); // @ts-expect-error gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); return status; } // WEBGL INTERFACE bind({target = GL.FRAMEBUFFER} = {}) { this.gl.bindFramebuffer(target, this.handle); return this; } unbind({target = GL.FRAMEBUFFER} = {}) { this.gl.bindFramebuffer(target, null); return this; } /** @note Expects framebuffer to be bound */ _setReadBuffer(readBuffer: number): void { const gl2 = getWebGL2Context(this.gl); if (gl2) { gl2.readBuffer(readBuffer); } else { // Setting to color attachment 0 is a noop, so allow it in WebGL1 assert( readBuffer === GL.COLOR_ATTACHMENT0 || readBuffer === GL.BACK, ERR_MULTIPLE_RENDERTARGETS ); } } /** @note Expects framebuffer to be bound */ _setDrawBuffers(drawBuffers: number[]) { const {gl} = this; const gl2 = assertWebGL2Context(gl); if (gl2) { gl2.drawBuffers(drawBuffers); } else { // TODO - is this not handled by polyfills? const ext = gl.getExtension('WEBGL_draw_buffers'); if (ext) { ext.drawBuffersWEBGL(drawBuffers); } else { // Setting a single draw buffer to color attachment 0 is a noop, allow in WebGL1 assert( drawBuffers.length === 1 && (drawBuffers[0] === GL.COLOR_ATTACHMENT0 || drawBuffers[0] === GL.BACK), ERR_MULTIPLE_RENDERTARGETS ); } } } // RESOURCE METHODS _createHandle() { return this.gl.createFramebuffer(); } _deleteHandle() { this.gl.deleteFramebuffer(this.handle); } _bindHandle(handle) { return this.gl.bindFramebuffer(GL.FRAMEBUFFER, handle); } update(options: { attachments: Record<string, Attachment | Renderbuffer>, readBuffer?: number, drawBuffers?, clearAttachments?: boolean, resizeAttachments?: boolean }): this { const { attachments = {}, readBuffer, drawBuffers, clearAttachments = false, resizeAttachments = true } = options; this.attach(attachments, {clearAttachments, resizeAttachments}); const {gl} = this; // Multiple render target support, set read buffer and draw buffers const prevHandle = gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); if (readBuffer) { this._setReadBuffer(readBuffer); this.readBuffer = readBuffer; } if (drawBuffers) { this._setDrawBuffers(drawBuffers); this.drawBuffers = drawBuffers; } // @ts-expect-error gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); return this; } /** Attach from a map of attachments */ attach(attachments, {clearAttachments = false, resizeAttachments = true} = {}) { const newAttachments = {}; // Any current attachments need to be removed, add null values to map if (clearAttachments) { Object.keys(this.attachments).forEach((key) => { newAttachments[key] = null; }); } // Overlay the new attachments Object.assign(newAttachments, attachments); const prevHandle = this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); // Walk the attachments for (const key in newAttachments) { // Ensure key is not undefined assert(key !== undefined, 'Misspelled framebuffer binding point?'); const attachment = Number(key); const descriptor = newAttachments[attachment]; let object = descriptor; if (!object) { this._unattach(attachment); } else { object = this._attachOne(attachment, object); this.attachments[attachment] = object; } // Resize objects if (resizeAttachments && object) { object.resize({width: this.width, height: this.height}); } } // @ts-expect-error this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); // Assign to attachments and remove any nulls to get a clean attachment map Object.assign(this.attachments, attachments); Object.keys(this.attachments) .filter((key) => !this.attachments[key]) .forEach((key) => { delete this.attachments[key]; }); } clear(options?: {color?: any; depth?: any; stencil?: any; drawBuffers?: any[]}): this { const {color, depth, stencil, drawBuffers = []} = options; // Bind framebuffer and delegate to global clear functions const prevHandle = this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); if (color || depth || stencil) { clear(this.gl, {color, depth, stencil}); } drawBuffers.forEach((value, drawBuffer) => { clearBuffer(this.gl, {drawBuffer, value}); }); // @ts-expect-error this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); return this; } // WEBGL2 INTERFACE // Copies a rectangle of pixels between framebuffers // eslint-disable-next-line complexity blit(opts = {}) { log.error('Framebuffer.blit({...}) is no logner supported, use blit(source, target, opts)')(); return null; } // signals to the GL that it need not preserve all pixels of a specified region of the framebuffer invalidate(options: {attachments: []; x?: number; y?: number; width: number; height: number}) { const {attachments = [], x = 0, y = 0, width, height} = options; const gl2 = assertWebGL2Context(this.gl); const prevHandle = gl2.bindFramebuffer(GL.READ_FRAMEBUFFER, this.handle); const invalidateAll = x === 0 && y === 0 && width === undefined && height === undefined; if (invalidateAll) { gl2.invalidateFramebuffer(GL.READ_FRAMEBUFFER, attachments); } else { // TODO - why does type checking fail on this line // @ts-expect-error gl2.invalidateFramebuffer(GL.READ_FRAMEBUFFER, attachments, x, y, width, height); } // @ts-expect-error gl2.bindFramebuffer(GL.READ_FRAMEBUFFER, prevHandle); return this; } // Return the value for `pname` of the specified attachment. // The type returned is the type of the requested pname getAttachmentParameter(attachment, pname, keys) { let value = this._getAttachmentParameterFallback(pname); if (value === null) { this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); value = this.gl.getFramebufferAttachmentParameter(GL.FRAMEBUFFER, attachment, pname); this.gl.bindFramebuffer(GL.FRAMEBUFFER, null); } if (keys && value > 1000) { // @ts-expect-error value = getKey(this.gl, value); } return value; } getAttachmentParameters( attachment = GL.COLOR_ATTACHMENT0, keys, // @ts-expect-error parameters = this.constructor.ATTACHMENT_PARAMETERS || [] ) { const values = {}; for (const pname of parameters) { const key = keys ? getKey(this.gl, pname) : pname; values[key] = this.getAttachmentParameter(attachment, pname, keys); } return values; } getParameters(keys = true) { const attachments = Object.keys(this.attachments); // if (this === this.gl.luma.defaultFramebuffer) { // attachments = [GL.COLOR_ATTACHMENT0, GL.DEPTH_STENCIL_ATTACHMENT]; // } const parameters = {}; for (const attachmentName of attachments) { const attachment = Number(attachmentName); const key = keys ? getKey(this.gl, attachment) : attachment; parameters[key] = this.getAttachmentParameters(attachment, keys); } return parameters; } // Note: Will only work when called in an event handler show() { if (typeof window !== 'undefined') { // window.open(copyToDataUrl(this), 'luma-debug-texture'); } return this; } log(logLevel = 0, message = '') { if (logLevel > log.level || typeof window === 'undefined') { return this; } message = message || `Framebuffer ${this.id}`; // const image = copyToDataUrl(this, {targetMaxHeight: 100}); // // @ts-expect-error probe.gl typings incorrectly require priority... // log.image({logLevel, message, image})(); return this; } // PRIVATE METHODS _unattach(attachment) { const oldAttachment = this.attachments[attachment]; if (!oldAttachment) { return; } if (oldAttachment instanceof Renderbuffer) { // render buffer this.gl.framebufferRenderbuffer(GL.FRAMEBUFFER, attachment, GL.RENDERBUFFER, null); } else { // Must be a texture attachment this.gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, GL.TEXTURE_2D, null, 0); } delete this.attachments[attachment]; } /** * Attempt to provide workable defaults for WebGL2 symbols under WebGL1 * null means OK to query * TODO - move to webgl1 polyfills * @param pname * @returns */ // eslint-disable-next-line complexity _getAttachmentParameterFallback(pname) { const webglDevice = WebGLDevice.attach(this.gl); const features = webglDevice.features; switch (pname) { case GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER: // GLint return !features.has('webgl2') ? 0 : null; case GL.FRAMEBUFFER_ATTACHMENT_RED_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE: // GLint return !features.has('webgl2') ? 8 : null; case GL.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE: // GLenum return !features.has('webgl2') ? GL.UNSIGNED_INT : null; case GL.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING: return !features.has('webgl2') && !features.has('texture-formats-srgb-webgl1') ? GL.LINEAR : null; default: return null; } } } // PUBLIC METHODS /** * Support * @param gl * @param options.colorBufferFloat Whether floating point textures can be rendered and read * @param options.colorBufferHalfFloat Whether half float textures can be rendered and read */ function isFloatColorBufferSupported( gl: WebGLRenderingContext, options: {colorBufferFloat?: boolean; colorBufferHalfFloat?: boolean} ): boolean { const { colorBufferFloat, // Whether floating point textures can be rendered and read colorBufferHalfFloat // Whether half float textures can be rendered and read } = options; let supported = true; if (colorBufferFloat) { supported = Boolean( // WebGL 2 gl.getExtension('EXT_color_buffer_float') || // WebGL 1, not exposed on all platforms gl.getExtension('WEBGL_color_buffer_float') || // WebGL 1, implicitly enables float render targets https://www.khronos.org/registry/webgl/extensions/OES_texture_float/ gl.getExtension('OES_texture_float') ); } if (colorBufferHalfFloat) { supported = supported && Boolean( // WebGL 2 gl.getExtension('EXT_color_buffer_float') || // WebGL 1 gl.getExtension('EXT_color_buffer_half_float') ); } return supported; }
{ "content_hash": "1e3364487cde63fbfb4de7d9bc0fe230", "timestamp": "", "source": "github", "line_count": 571, "max_line_length": 128, "avg_line_length": 32.714535901926446, "alnum_prop": 0.6657922912205567, "repo_name": "uber-common/luma.gl", "id": "f21320c2fafd8ddcc476f8fe3b6f207af232816c", "size": "18680", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/gltools/src/classic/framebuffer.ts", "mode": "33188", "license": "mit", "language": [ { "name": "GLSL", "bytes": "12808" }, { "name": "HTML", "bytes": "6495" }, { "name": "JavaScript", "bytes": "567714" } ], "symlink_target": "" }
package org.springframework.boot.autoconfigure.mustache; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Mustache.Collector; import com.samskivert.mustache.Mustache.TemplateLoader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.template.TemplateLocation; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.env.Environment; /** * {@link EnableAutoConfiguration Auto-configuration} for Mustache. * * @author Dave Syer * @author Brian Clozel * @since 1.2.2 */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Mustache.class) @EnableConfigurationProperties(MustacheProperties.class) @Import({ MustacheServletWebConfiguration.class, MustacheReactiveWebConfiguration.class }) public class MustacheAutoConfiguration { private static final Log logger = LogFactory.getLog(MustacheAutoConfiguration.class); private final MustacheProperties mustache; private final ApplicationContext applicationContext; public MustacheAutoConfiguration(MustacheProperties mustache, ApplicationContext applicationContext) { this.mustache = mustache; this.applicationContext = applicationContext; checkTemplateLocationExists(); } public void checkTemplateLocationExists() { if (this.mustache.isCheckTemplateLocation()) { TemplateLocation location = new TemplateLocation(this.mustache.getPrefix()); if (!location.exists(this.applicationContext) && logger.isWarnEnabled()) { logger.warn("Cannot find template location: " + location + " (please add some templates, check your Mustache configuration, or set spring.mustache." + "check-template-location=false)"); } } } @Bean @ConditionalOnMissingBean public Mustache.Compiler mustacheCompiler(TemplateLoader mustacheTemplateLoader, Environment environment) { return Mustache.compiler().withLoader(mustacheTemplateLoader).withCollector(collector(environment)); } private Collector collector(Environment environment) { MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector(); collector.setEnvironment(environment); return collector; } @Bean @ConditionalOnMissingBean(TemplateLoader.class) public MustacheResourceTemplateLoader mustacheTemplateLoader() { MustacheResourceTemplateLoader loader = new MustacheResourceTemplateLoader(this.mustache.getPrefix(), this.mustache.getSuffix()); loader.setCharset(this.mustache.getCharsetName()); return loader; } }
{ "content_hash": "de28f2835e68cda2272adb1399f9156a", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 108, "avg_line_length": 38.139240506329116, "alnum_prop": 0.8221042150680385, "repo_name": "mbenson/spring-boot", "id": "eb093acc5f1d55104e038e2c4ebc4500ad5bf3df", "size": "3634", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1948" }, { "name": "CSS", "bytes": "5769" }, { "name": "Dockerfile", "bytes": "5379" }, { "name": "FreeMarker", "bytes": "3599" }, { "name": "Groovy", "bytes": "51602" }, { "name": "HTML", "bytes": "69601" }, { "name": "Java", "bytes": "14060047" }, { "name": "JavaScript", "bytes": "37789" }, { "name": "Kotlin", "bytes": "25029" }, { "name": "Ruby", "bytes": "1308" }, { "name": "Shell", "bytes": "31639" }, { "name": "Smarty", "bytes": "2885" }, { "name": "XSLT", "bytes": "36394" } ], "symlink_target": "" }
package com.antsoft.ant.pool.classpool; import java.lang.reflect.*; import java.util.Hashtable; import java.util.Vector; import javax.swing.table.TableModel; import com.antsoft.ant.util.*; import com.antsoft.ant.pool.librarypool.*; import com.antsoft.ant.manager.projectmanager.*; /** * classÀÇ reflection Á¤º¸¸¦ Á¦°øÇÑ´Ù * * @author Kim sang kyun */ public final class ClassPool { //exist¸¦ È£Ãâ ÇßÀ»¶§ loadÇØ³õÀº class instance private static Class cachedInstance; /** * interfaceÀÎÁö ¾Æ´ÑÁö Á¤º¸¸¦ Á¦°ø. package browser¿¡¼­ óÀ½¿¡ * class list¸¦ º¸¿©ÁÙ¶§ »ç¿ëÇÑ´Ù * * @param fullClassName classname * @return interfaceÀÎÁö classÀÎÁö Á¤º¸ */ public static final boolean isInterface(String fullClassName) throws java.lang.ClassNotFoundException{ Class instance = getClassInstance(fullClassName); if(instance != null){ return instance.isInterface(); } else return false; } /** * class instance¸¦ ¹ÝȯÇÑ´Ù * * @param fullClassName key * @return class instance */ public static Class getClassInstance(String fullClassName){ if( (cachedInstance != null) && cachedInstance.getName().equals(fullClassName)) { return cachedInstance; } Class instance = null; try{ instance = createClassInstance(fullClassName); cachedInstance = instance; }catch(ClassNotFoundException e){ instance = null; } return instance; } /** * class instance°¡ Á¸ÀçÇÏ´ÂÁö ¾Ë¾Æº»´Ù * * @param fullClassName fullClassName to Search * @return exist or not flag */ public static boolean exist(String fullClassName){ if( (cachedInstance != null) && cachedInstance.getName().equals(fullClassName)) return true; FileClassLoader loader = ProjectManager.getCurrentProject().getClassLoader(); if(loader == null) return false; Class instance = null; try{ instance = loader.loadClass(fullClassName, true); }catch(Exception e){ return false; } if(instance == null) return false; else { cachedInstance = instance; return true; } } /** * class instance¸¦ ¾ò´Â´Ù * * @param fullClassName classname * @return Class instance */ private static Class createClassInstance(String fullClassName) throws java.lang.ClassNotFoundException{ Class loaded = null; FileClassLoader classLoader = ProjectManager.getCurrentProject().getClassLoader(); if(classLoader == null) { System.out.println("Class Loader is NULL"); throw new ClassNotFoundException("CurrentProject's ClassLoader is NULL"); } try{ loaded = classLoader.loadClass(fullClassName, true); }catch(Exception e){ e.printStackTrace(); return null; } return loaded; } /** * get super class vector */ private static Vector superClasses = new Vector(4, 2); public static final Vector getSuperClasses(String fullClassName){ if(superClasses.size() > 0) superClasses.removeAllElements(); Class instance = getClassInstance(fullClassName); if(instance == null) return null; superClasses.addElement(fullClassName); instance = instance.getSuperclass(); while(instance != null){ superClasses.addElement(instance.getName()); instance = instance.getSuperclass(); } return superClasses; } /** * ƯÁ¤ classÀÇ static field name list¸¦ ¾ò´Â´Ù * * @param fullClassName classname * @return static field name list */ public static final Vector getStaticFieldSignatures(String fullClassName){ Vector ret = new Vector(15, 5); Vector signatures = getFieldSignatures(fullClassName); if(signatures != null){ for(int i=0; i<signatures.size(); i++){ SigModelImpl sig = (SigModelImpl)signatures.elementAt(i); if(sig.isStatic()) ret.addElement(sig); } return ret; } else { // it must be not happened.. return null; } } /** * ƯÁ¤ classÀÇ field name list¸¦ ¾ò´Â´Ù. public Àΰ͸¸ ¸®ÅÏ * * @param fullClassName classname * @return field name list */ public static final Vector getFieldSignatures(String fullClassName){ Class classInstance = getClassInstance(fullClassName); if(classInstance == null) return null; Hashtable tempHash = new Hashtable(20, 0.9F); //mine Field [] mine_fields = classInstance.getDeclaredFields(); Vector signatures = new Vector(); for(int i=0; i<mine_fields.length; i++){ if(!Modifier.isPublic( mine_fields[i].getModifiers() )) continue; SigModelImpl model = new SigModelImpl(SigModelImpl.FIELD, mine_fields[i].getName(), fullClassName, mine_fields[i].getType(), Modifier.isStatic(mine_fields[i].getModifiers()), true); signatures.addElement(model); tempHash.put(mine_fields[i].getName(), ""); } //inherit Field [] inherit_fields = classInstance.getFields(); for(int i=0; i<inherit_fields.length; i++){ if(tempHash.get(inherit_fields[i].getName()) != null) continue; if(!(Modifier.isPublic( inherit_fields[i].getModifiers() ) || Modifier.isProtected( inherit_fields[i].getModifiers() ))) continue; SigModelImpl model = new SigModelImpl(SigModelImpl.FIELD, inherit_fields[i].getName(), fullClassName, inherit_fields[i].getType(), Modifier.isStatic(inherit_fields[i].getModifiers()), false); signatures.addElement(model); } signatures = getSortedNames(signatures); return signatures; } /** * ƯÁ¤ classÀÇ constructor name list¸¦ ¾ò´Â´Ù * * @param fullClassName classname * @return constructor name list */ public static final Vector getConstructorSignatures(String fullClassName){ Class classInstance = getClassInstance(fullClassName); if(classInstance == null) return null; Constructor [] constructors = classInstance.getConstructors(); Vector signatures = new Vector(); for(int i=0; i<constructors.length; i++){ SigModelImpl sigModel = new SigModelImpl(SigModelImpl.CONSTRUCTOR, constructors[i].getName(), fullClassName, null, false, true, constructors[i].getParameterTypes()); signatures.addElement(sigModel); } signatures = getSortedNames(signatures); return signatures; } /** * ƯÁ¤ classÀÇ static method name list¸¦ ¾ò´Â´Ù * * @param fullClassName classname * @return static method name list */ public static final Vector getStaticMethodSignatures(String fullClassName){ Vector ret = new Vector(15, 5); Vector signatures = getMethodSignatures(fullClassName); if(signatures != null) { for(int i=0; i<signatures.size(); i++){ SigModelImpl sig = (SigModelImpl)signatures.elementAt(i); if(sig.isStatic()) ret.addElement(sig); } return ret; } else { // it must be not happened.. return null; } } /** * ƯÁ¤ classÀÇ method name list¸¦ ¾ò´Â´Ù * * @param fullClassName classname * @return method name list */ public static final Vector getMethodSignatures(String fullClassName){ Class classInstance = getClassInstance(fullClassName); if(classInstance == null) return null; Hashtable tempHash = new Hashtable(20, 0.9F); //mine Method [] mine_methods = classInstance.getDeclaredMethods(); Vector signatures = new Vector(); for(int i=0; i<mine_methods.length; i++){ if(!Modifier.isPublic( mine_methods[i].getModifiers() )) continue; SigModelImpl model = new SigModelImpl(SigModelImpl.METHOD, mine_methods[i].getName(), fullClassName, mine_methods[i].getReturnType(), Modifier.isStatic(mine_methods[i].getModifiers()), true, mine_methods[i].getParameterTypes() ); signatures.addElement(model); tempHash.put(mine_methods[i].getName(), ""); } //inherit Method [] inherit_methods = classInstance.getMethods(); for(int i=0; i<inherit_methods.length; i++){ if(tempHash.get(inherit_methods[i].getName()) != null ) continue; if(!(Modifier.isPublic( inherit_methods[i].getModifiers() ) || Modifier.isProtected( inherit_methods[i].getModifiers() ))) continue; SigModelImpl model = new SigModelImpl(SigModelImpl.METHOD, inherit_methods[i].getName(), fullClassName, inherit_methods[i].getReturnType(), Modifier.isStatic(inherit_methods[i].getModifiers()), false, inherit_methods[i].getParameterTypes() ); signatures.addElement(model); } return signatures; } /** * sorting ½ÃÄÑÁØ´Ù * * @param unSorted unsorted vector * @return sorted vector */ public static final Vector getSortedNames(Vector unSorted) { Hashtable dataH = new Hashtable(); Vector dataV = new Vector(); Vector returnV = new Vector(); for(int i=0; i<unSorted.size(); i++){ SigModelImpl sigModel = (SigModelImpl)unSorted.elementAt(i); dataH.put(sigModel.toString(), sigModel); dataV.addElement(sigModel.toString()); } dataV = QuickSorter.sort(dataV, QuickSorter.LESS_STRING); for(int i=0; i<dataV.size(); i++){ returnV.addElement((SigModelImpl)dataH.get((String)dataV.elementAt(i))); } return returnV; } /** * return super class name */ public static final String getSuperClass(String fullClassName){ Class original = getClassInstance(fullClassName); if(original == null) return null; if(original.getSuperclass() == null) return null; else return original.getSuperclass().getName(); } }
{ "content_hash": "88cba889434e58c5b83d9bfe8422a71b", "timestamp": "", "source": "github", "line_count": 333, "max_line_length": 139, "avg_line_length": 30.91891891891892, "alnum_prop": 0.6184926184926185, "repo_name": "FJplant/AntIDE", "id": "2d125622f94d204111cad62e3bc131b67477d26f", "size": "10855", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/antsoft/ant/pool/classpool/ClassPool.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1806" }, { "name": "HTML", "bytes": "27541" }, { "name": "Java", "bytes": "4609672" }, { "name": "Shell", "bytes": "5614" } ], "symlink_target": "" }
/* $NetBSD: suff.c,v 1.70 2013/05/18 13:13:34 sjg Exp $ */ /* * Copyright (c) 1988, 1989, 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (c) 1989 by Berkeley Softworks * All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef MAKE_NATIVE static char rcsid[] = "$NetBSD: suff.c,v 1.70 2013/05/18 13:13:34 sjg Exp $"; #else #include <sys/cdefs.h> #ifndef lint #if 0 static char sccsid[] = "@(#)suff.c 8.4 (Berkeley) 3/21/94"; #else __RCSID("$NetBSD: suff.c,v 1.70 2013/05/18 13:13:34 sjg Exp $"); #endif #endif /* not lint */ #endif /*- * suff.c -- * Functions to maintain suffix lists and find implicit dependents * using suffix transformation rules * * Interface: * Suff_Init Initialize all things to do with suffixes. * * Suff_End Cleanup the module * * Suff_DoPaths This function is used to make life easier * when searching for a file according to its * suffix. It takes the global search path, * as defined using the .PATH: target, and appends * its directories to the path of each of the * defined suffixes, as specified using * .PATH<suffix>: targets. In addition, all * directories given for suffixes labeled as * include files or libraries, using the .INCLUDES * or .LIBS targets, are played with using * Dir_MakeFlags to create the .INCLUDES and * .LIBS global variables. * * Suff_ClearSuffixes Clear out all the suffixes and defined * transformations. * * Suff_IsTransform Return TRUE if the passed string is the lhs * of a transformation rule. * * Suff_AddSuffix Add the passed string as another known suffix. * * Suff_GetPath Return the search path for the given suffix. * * Suff_AddInclude Mark the given suffix as denoting an include * file. * * Suff_AddLib Mark the given suffix as denoting a library. * * Suff_AddTransform Add another transformation to the suffix * graph. Returns GNode suitable for framing, I * mean, tacking commands, attributes, etc. on. * * Suff_SetNull Define the suffix to consider the suffix of * any file that doesn't have a known one. * * Suff_FindDeps Find implicit sources for and the location of * a target based on its suffix. Returns the * bottom-most node added to the graph or NULL * if the target had no implicit sources. * * Suff_FindPath Return the appropriate path to search in * order to find the node. */ #include <stdio.h> #include "make.h" #include "hash.h" #include "dir.h" static Lst sufflist; /* Lst of suffixes */ #ifdef CLEANUP static Lst suffClean; /* Lst of suffixes to be cleaned */ #endif static Lst srclist; /* Lst of sources */ static Lst transforms; /* Lst of transformation rules */ static int sNum = 0; /* Counter for assigning suffix numbers */ /* * Structure describing an individual suffix. */ typedef struct _Suff { char *name; /* The suffix itself */ int nameLen; /* Length of the suffix */ short flags; /* Type of suffix */ #define SUFF_INCLUDE 0x01 /* One which is #include'd */ #define SUFF_LIBRARY 0x02 /* One which contains a library */ #define SUFF_NULL 0x04 /* The empty suffix */ Lst searchPath; /* The path along which files of this suffix * may be found */ int sNum; /* The suffix number */ int refCount; /* Reference count of list membership */ Lst parents; /* Suffixes we have a transformation to */ Lst children; /* Suffixes we have a transformation from */ Lst ref; /* List of lists this suffix is referenced */ } Suff; /* * for SuffSuffIsSuffix */ typedef struct { char *ename; /* The end of the name */ int len; /* Length of the name */ } SuffixCmpData; /* * Structure used in the search for implied sources. */ typedef struct _Src { char *file; /* The file to look for */ char *pref; /* Prefix from which file was formed */ Suff *suff; /* The suffix on the file */ struct _Src *parent; /* The Src for which this is a source */ GNode *node; /* The node describing the file */ int children; /* Count of existing children (so we don't free * this thing too early or never nuke it) */ #ifdef DEBUG_SRC Lst cp; /* Debug; children list */ #endif } Src; /* * A structure for passing more than one argument to the Lst-library-invoked * function... */ typedef struct { Lst l; Src *s; } LstSrc; typedef struct { GNode **gn; Suff *s; Boolean r; } GNodeSuff; static Suff *suffNull; /* The NULL suffix for this run */ static Suff *emptySuff; /* The empty suffix required for POSIX * single-suffix transformation rules */ static const char *SuffStrIsPrefix(const char *, const char *); static char *SuffSuffIsSuffix(const Suff *, const SuffixCmpData *); static int SuffSuffIsSuffixP(const void *, const void *); static int SuffSuffHasNameP(const void *, const void *); static int SuffSuffIsPrefix(const void *, const void *); static int SuffGNHasNameP(const void *, const void *); static void SuffUnRef(void *, void *); static void SuffFree(void *); static void SuffInsert(Lst, Suff *); static void SuffRemove(Lst, Suff *); static Boolean SuffParseTransform(char *, Suff **, Suff **); static int SuffRebuildGraph(void *, void *); static int SuffScanTargets(void *, void *); static int SuffAddSrc(void *, void *); static int SuffRemoveSrc(Lst); static void SuffAddLevel(Lst, Src *); static Src *SuffFindThem(Lst, Lst); static Src *SuffFindCmds(Src *, Lst); static void SuffExpandChildren(LstNode, GNode *); static void SuffExpandWildcards(LstNode, GNode *); static Boolean SuffApplyTransform(GNode *, GNode *, Suff *, Suff *); static void SuffFindDeps(GNode *, Lst); static void SuffFindArchiveDeps(GNode *, Lst); static void SuffFindNormalDeps(GNode *, Lst); static int SuffPrintName(void *, void *); static int SuffPrintSuff(void *, void *); static int SuffPrintTrans(void *, void *); /*************** Lst Predicates ****************/ /*- *----------------------------------------------------------------------- * SuffStrIsPrefix -- * See if pref is a prefix of str. * * Input: * pref possible prefix * str string to check * * Results: * NULL if it ain't, pointer to character in str after prefix if so * * Side Effects: * None *----------------------------------------------------------------------- */ static const char * SuffStrIsPrefix(const char *pref, const char *str) { while (*str && *pref == *str) { pref++; str++; } return (*pref ? NULL : str); } /*- *----------------------------------------------------------------------- * SuffSuffIsSuffix -- * See if suff is a suffix of str. sd->ename should point to THE END * of the string to check. (THE END == the null byte) * * Input: * s possible suffix * sd string to examine * * Results: * NULL if it ain't, pointer to character in str before suffix if * it is. * * Side Effects: * None *----------------------------------------------------------------------- */ static char * SuffSuffIsSuffix(const Suff *s, const SuffixCmpData *sd) { char *p1; /* Pointer into suffix name */ char *p2; /* Pointer into string being examined */ if (sd->len < s->nameLen) return NULL; /* this string is shorter than the suffix */ p1 = s->name + s->nameLen; p2 = sd->ename; while (p1 >= s->name && *p1 == *p2) { p1--; p2--; } return (p1 == s->name - 1 ? p2 : NULL); } /*- *----------------------------------------------------------------------- * SuffSuffIsSuffixP -- * Predicate form of SuffSuffIsSuffix. Passed as the callback function * to Lst_Find. * * Results: * 0 if the suffix is the one desired, non-zero if not. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static int SuffSuffIsSuffixP(const void *s, const void *sd) { return(!SuffSuffIsSuffix(s, sd)); } /*- *----------------------------------------------------------------------- * SuffSuffHasNameP -- * Callback procedure for finding a suffix based on its name. Used by * Suff_GetPath. * * Input: * s Suffix to check * sd Desired name * * Results: * 0 if the suffix is of the given name. non-zero otherwise. * * Side Effects: * None *----------------------------------------------------------------------- */ static int SuffSuffHasNameP(const void *s, const void *sname) { return (strcmp(sname, ((const Suff *)s)->name)); } /*- *----------------------------------------------------------------------- * SuffSuffIsPrefix -- * See if the suffix described by s is a prefix of the string. Care * must be taken when using this to search for transformations and * what-not, since there could well be two suffixes, one of which * is a prefix of the other... * * Input: * s suffix to compare * str string to examine * * Results: * 0 if s is a prefix of str. non-zero otherwise * * Side Effects: * None *----------------------------------------------------------------------- */ static int SuffSuffIsPrefix(const void *s, const void *str) { return SuffStrIsPrefix(((const Suff *)s)->name, str) == NULL; } /*- *----------------------------------------------------------------------- * SuffGNHasNameP -- * See if the graph node has the desired name * * Input: * gn current node we're looking at * name name we're looking for * * Results: * 0 if it does. non-zero if it doesn't * * Side Effects: * None *----------------------------------------------------------------------- */ static int SuffGNHasNameP(const void *gn, const void *name) { return (strcmp(name, ((const GNode *)gn)->name)); } /*********** Maintenance Functions ************/ static void SuffUnRef(void *lp, void *sp) { Lst l = (Lst) lp; LstNode ln = Lst_Member(l, sp); if (ln != NULL) { Lst_Remove(l, ln); ((Suff *)sp)->refCount--; } } /*- *----------------------------------------------------------------------- * SuffFree -- * Free up all memory associated with the given suffix structure. * * Results: * none * * Side Effects: * the suffix entry is detroyed *----------------------------------------------------------------------- */ static void SuffFree(void *sp) { Suff *s = (Suff *)sp; if (s == suffNull) suffNull = NULL; if (s == emptySuff) emptySuff = NULL; #ifdef notdef /* We don't delete suffixes in order, so we cannot use this */ if (s->refCount) Punt("Internal error deleting suffix `%s' with refcount = %d", s->name, s->refCount); #endif Lst_Destroy(s->ref, NULL); Lst_Destroy(s->children, NULL); Lst_Destroy(s->parents, NULL); Lst_Destroy(s->searchPath, Dir_Destroy); free(s->name); free(s); } /*- *----------------------------------------------------------------------- * SuffRemove -- * Remove the suffix into the list * * Results: * None * * Side Effects: * The reference count for the suffix is decremented and the * suffix is possibly freed *----------------------------------------------------------------------- */ static void SuffRemove(Lst l, Suff *s) { SuffUnRef(l, s); if (s->refCount == 0) { SuffUnRef(sufflist, s); SuffFree(s); } } /*- *----------------------------------------------------------------------- * SuffInsert -- * Insert the suffix into the list keeping the list ordered by suffix * numbers. * * Input: * l the list where in s should be inserted * s the suffix to insert * * Results: * None * * Side Effects: * The reference count of the suffix is incremented *----------------------------------------------------------------------- */ static void SuffInsert(Lst l, Suff *s) { LstNode ln; /* current element in l we're examining */ Suff *s2 = NULL; /* the suffix descriptor in this element */ if (Lst_Open(l) == FAILURE) { return; } while ((ln = Lst_Next(l)) != NULL) { s2 = (Suff *)Lst_Datum(ln); if (s2->sNum >= s->sNum) { break; } } Lst_Close(l); if (DEBUG(SUFF)) { fprintf(debug_file, "inserting %s(%d)...", s->name, s->sNum); } if (ln == NULL) { if (DEBUG(SUFF)) { fprintf(debug_file, "at end of list\n"); } (void)Lst_AtEnd(l, s); s->refCount++; (void)Lst_AtEnd(s->ref, l); } else if (s2->sNum != s->sNum) { if (DEBUG(SUFF)) { fprintf(debug_file, "before %s(%d)\n", s2->name, s2->sNum); } (void)Lst_InsertBefore(l, ln, s); s->refCount++; (void)Lst_AtEnd(s->ref, l); } else if (DEBUG(SUFF)) { fprintf(debug_file, "already there\n"); } } /*- *----------------------------------------------------------------------- * Suff_ClearSuffixes -- * This is gross. Nuke the list of suffixes but keep all transformation * rules around. The transformation graph is destroyed in this process, * but we leave the list of rules so when a new graph is formed the rules * will remain. * This function is called from the parse module when a * .SUFFIXES:\n line is encountered. * * Results: * none * * Side Effects: * the sufflist and its graph nodes are destroyed *----------------------------------------------------------------------- */ void Suff_ClearSuffixes(void) { #ifdef CLEANUP Lst_Concat(suffClean, sufflist, LST_CONCLINK); #endif sufflist = Lst_Init(FALSE); sNum = 0; suffNull = emptySuff; } /*- *----------------------------------------------------------------------- * SuffParseTransform -- * Parse a transformation string to find its two component suffixes. * * Input: * str String being parsed * srcPtr Place to store source of trans. * targPtr Place to store target of trans. * * Results: * TRUE if the string is a valid transformation and FALSE otherwise. * * Side Effects: * The passed pointers are overwritten. * *----------------------------------------------------------------------- */ static Boolean SuffParseTransform(char *str, Suff **srcPtr, Suff **targPtr) { LstNode srcLn; /* element in suffix list of trans source*/ Suff *src; /* Source of transformation */ LstNode targLn; /* element in suffix list of trans target*/ char *str2; /* Extra pointer (maybe target suffix) */ LstNode singleLn; /* element in suffix list of any suffix * that exactly matches str */ Suff *single = NULL;/* Source of possible transformation to * null suffix */ srcLn = NULL; singleLn = NULL; /* * Loop looking first for a suffix that matches the start of the * string and then for one that exactly matches the rest of it. If * we can find two that meet these criteria, we've successfully * parsed the string. */ for (;;) { if (srcLn == NULL) { srcLn = Lst_Find(sufflist, str, SuffSuffIsPrefix); } else { srcLn = Lst_FindFrom(sufflist, Lst_Succ(srcLn), str, SuffSuffIsPrefix); } if (srcLn == NULL) { /* * Ran out of source suffixes -- no such rule */ if (singleLn != NULL) { /* * Not so fast Mr. Smith! There was a suffix that encompassed * the entire string, so we assume it was a transformation * to the null suffix (thank you POSIX). We still prefer to * find a double rule over a singleton, hence we leave this * check until the end. * * XXX: Use emptySuff over suffNull? */ *srcPtr = single; *targPtr = suffNull; return(TRUE); } return (FALSE); } src = (Suff *)Lst_Datum(srcLn); str2 = str + src->nameLen; if (*str2 == '\0') { single = src; singleLn = srcLn; } else { targLn = Lst_Find(sufflist, str2, SuffSuffHasNameP); if (targLn != NULL) { *srcPtr = src; *targPtr = (Suff *)Lst_Datum(targLn); return (TRUE); } } } } /*- *----------------------------------------------------------------------- * Suff_IsTransform -- * Return TRUE if the given string is a transformation rule * * * Input: * str string to check * * Results: * TRUE if the string is a concatenation of two known suffixes. * FALSE otherwise * * Side Effects: * None *----------------------------------------------------------------------- */ Boolean Suff_IsTransform(char *str) { Suff *src, *targ; return (SuffParseTransform(str, &src, &targ)); } /*- *----------------------------------------------------------------------- * Suff_AddTransform -- * Add the transformation rule described by the line to the * list of rules and place the transformation itself in the graph * * Input: * line name of transformation to add * * Results: * The node created for the transformation in the transforms list * * Side Effects: * The node is placed on the end of the transforms Lst and links are * made between the two suffixes mentioned in the target name *----------------------------------------------------------------------- */ GNode * Suff_AddTransform(char *line) { GNode *gn; /* GNode of transformation rule */ Suff *s, /* source suffix */ *t; /* target suffix */ LstNode ln; /* Node for existing transformation */ ln = Lst_Find(transforms, line, SuffGNHasNameP); if (ln == NULL) { /* * Make a new graph node for the transformation. It will be filled in * by the Parse module. */ gn = Targ_NewGN(line); (void)Lst_AtEnd(transforms, gn); } else { /* * New specification for transformation rule. Just nuke the old list * of commands so they can be filled in again... We don't actually * free the commands themselves, because a given command can be * attached to several different transformations. */ gn = (GNode *)Lst_Datum(ln); Lst_Destroy(gn->commands, NULL); Lst_Destroy(gn->children, NULL); gn->commands = Lst_Init(FALSE); gn->children = Lst_Init(FALSE); } gn->type = OP_TRANSFORM; (void)SuffParseTransform(line, &s, &t); /* * link the two together in the proper relationship and order */ if (DEBUG(SUFF)) { fprintf(debug_file, "defining transformation from `%s' to `%s'\n", s->name, t->name); } SuffInsert(t->children, s); SuffInsert(s->parents, t); return (gn); } /*- *----------------------------------------------------------------------- * Suff_EndTransform -- * Handle the finish of a transformation definition, removing the * transformation from the graph if it has neither commands nor * sources. This is a callback procedure for the Parse module via * Lst_ForEach * * Input: * gnp Node for transformation * dummy Node for transformation * * Results: * === 0 * * Side Effects: * If the node has no commands or children, the children and parents * lists of the affected suffixes are altered. * *----------------------------------------------------------------------- */ int Suff_EndTransform(void *gnp, void *dummy) { GNode *gn = (GNode *)gnp; if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts)) gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts)); if ((gn->type & OP_TRANSFORM) && Lst_IsEmpty(gn->commands) && Lst_IsEmpty(gn->children)) { Suff *s, *t; /* * SuffParseTransform() may fail for special rules which are not * actual transformation rules. (e.g. .DEFAULT) */ if (SuffParseTransform(gn->name, &s, &t)) { Lst p; if (DEBUG(SUFF)) { fprintf(debug_file, "deleting transformation from `%s' to `%s'\n", s->name, t->name); } /* * Store s->parents because s could be deleted in SuffRemove */ p = s->parents; /* * Remove the source from the target's children list. We check for a * nil return to handle a beanhead saying something like * .c.o .c.o: * * We'll be called twice when the next target is seen, but .c and .o * are only linked once... */ SuffRemove(t->children, s); /* * Remove the target from the source's parents list */ SuffRemove(p, t); } } else if ((gn->type & OP_TRANSFORM) && DEBUG(SUFF)) { fprintf(debug_file, "transformation %s complete\n", gn->name); } return(dummy ? 0 : 0); } /*- *----------------------------------------------------------------------- * SuffRebuildGraph -- * Called from Suff_AddSuffix via Lst_ForEach to search through the * list of existing transformation rules and rebuild the transformation * graph when it has been destroyed by Suff_ClearSuffixes. If the * given rule is a transformation involving this suffix and another, * existing suffix, the proper relationship is established between * the two. * * Input: * transformp Transformation to test * sp Suffix to rebuild * * Results: * Always 0. * * Side Effects: * The appropriate links will be made between this suffix and * others if transformation rules exist for it. * *----------------------------------------------------------------------- */ static int SuffRebuildGraph(void *transformp, void *sp) { GNode *transform = (GNode *)transformp; Suff *s = (Suff *)sp; char *cp; LstNode ln; Suff *s2; SuffixCmpData sd; /* * First see if it is a transformation from this suffix. */ cp = UNCONST(SuffStrIsPrefix(s->name, transform->name)); if (cp != NULL) { ln = Lst_Find(sufflist, cp, SuffSuffHasNameP); if (ln != NULL) { /* * Found target. Link in and return, since it can't be anything * else. */ s2 = (Suff *)Lst_Datum(ln); SuffInsert(s2->children, s); SuffInsert(s->parents, s2); return(0); } } /* * Not from, maybe to? */ sd.len = strlen(transform->name); sd.ename = transform->name + sd.len; cp = SuffSuffIsSuffix(s, &sd); if (cp != NULL) { /* * Null-terminate the source suffix in order to find it. */ cp[1] = '\0'; ln = Lst_Find(sufflist, transform->name, SuffSuffHasNameP); /* * Replace the start of the target suffix */ cp[1] = s->name[0]; if (ln != NULL) { /* * Found it -- establish the proper relationship */ s2 = (Suff *)Lst_Datum(ln); SuffInsert(s->children, s2); SuffInsert(s2->parents, s); } } return(0); } /*- *----------------------------------------------------------------------- * SuffScanTargets -- * Called from Suff_AddSuffix via Lst_ForEach to search through the * list of existing targets and find if any of the existing targets * can be turned into a transformation rule. * * Results: * 1 if a new main target has been selected, 0 otherwise. * * Side Effects: * If such a target is found and the target is the current main * target, the main target is set to NULL and the next target * examined (if that exists) becomes the main target. * *----------------------------------------------------------------------- */ static int SuffScanTargets(void *targetp, void *gsp) { GNode *target = (GNode *)targetp; GNodeSuff *gs = (GNodeSuff *)gsp; Suff *s, *t; char *ptr; if (*gs->gn == NULL && gs->r && (target->type & OP_NOTARGET) == 0) { *gs->gn = target; Targ_SetMain(target); return 1; } if ((unsigned int)target->type == OP_TRANSFORM) return 0; if ((ptr = strstr(target->name, gs->s->name)) == NULL || ptr == target->name) return 0; if (SuffParseTransform(target->name, &s, &t)) { if (*gs->gn == target) { gs->r = TRUE; *gs->gn = NULL; Targ_SetMain(NULL); } Lst_Destroy(target->children, NULL); target->children = Lst_Init(FALSE); target->type = OP_TRANSFORM; /* * link the two together in the proper relationship and order */ if (DEBUG(SUFF)) { fprintf(debug_file, "defining transformation from `%s' to `%s'\n", s->name, t->name); } SuffInsert(t->children, s); SuffInsert(s->parents, t); } return 0; } /*- *----------------------------------------------------------------------- * Suff_AddSuffix -- * Add the suffix in string to the end of the list of known suffixes. * Should we restructure the suffix graph? Make doesn't... * * Input: * str the name of the suffix to add * * Results: * None * * Side Effects: * A GNode is created for the suffix and a Suff structure is created and * added to the suffixes list unless the suffix was already known. * The mainNode passed can be modified if a target mutated into a * transform and that target happened to be the main target. *----------------------------------------------------------------------- */ void Suff_AddSuffix(char *str, GNode **gn) { Suff *s; /* new suffix descriptor */ LstNode ln; GNodeSuff gs; ln = Lst_Find(sufflist, str, SuffSuffHasNameP); if (ln == NULL) { s = bmake_malloc(sizeof(Suff)); s->name = bmake_strdup(str); s->nameLen = strlen(s->name); s->searchPath = Lst_Init(FALSE); s->children = Lst_Init(FALSE); s->parents = Lst_Init(FALSE); s->ref = Lst_Init(FALSE); s->sNum = sNum++; s->flags = 0; s->refCount = 1; (void)Lst_AtEnd(sufflist, s); /* * We also look at our existing targets list to see if adding * this suffix will make one of our current targets mutate into * a suffix rule. This is ugly, but other makes treat all targets * that start with a . as suffix rules. */ gs.gn = gn; gs.s = s; gs.r = FALSE; Lst_ForEach(Targ_List(), SuffScanTargets, &gs); /* * Look for any existing transformations from or to this suffix. * XXX: Only do this after a Suff_ClearSuffixes? */ Lst_ForEach(transforms, SuffRebuildGraph, s); } } /*- *----------------------------------------------------------------------- * Suff_GetPath -- * Return the search path for the given suffix, if it's defined. * * Results: * The searchPath for the desired suffix or NULL if the suffix isn't * defined. * * Side Effects: * None *----------------------------------------------------------------------- */ Lst Suff_GetPath(char *sname) { LstNode ln; Suff *s; ln = Lst_Find(sufflist, sname, SuffSuffHasNameP); if (ln == NULL) { return NULL; } else { s = (Suff *)Lst_Datum(ln); return (s->searchPath); } } /*- *----------------------------------------------------------------------- * Suff_DoPaths -- * Extend the search paths for all suffixes to include the default * search path. * * Results: * None. * * Side Effects: * The searchPath field of all the suffixes is extended by the * directories in dirSearchPath. If paths were specified for the * ".h" suffix, the directories are stuffed into a global variable * called ".INCLUDES" with each directory preceded by a -I. The same * is done for the ".a" suffix, except the variable is called * ".LIBS" and the flag is -L. *----------------------------------------------------------------------- */ void Suff_DoPaths(void) { Suff *s; LstNode ln; char *ptr; Lst inIncludes; /* Cumulative .INCLUDES path */ Lst inLibs; /* Cumulative .LIBS path */ if (Lst_Open(sufflist) == FAILURE) { return; } inIncludes = Lst_Init(FALSE); inLibs = Lst_Init(FALSE); while ((ln = Lst_Next(sufflist)) != NULL) { s = (Suff *)Lst_Datum(ln); if (!Lst_IsEmpty (s->searchPath)) { #ifdef INCLUDES if (s->flags & SUFF_INCLUDE) { Dir_Concat(inIncludes, s->searchPath); } #endif /* INCLUDES */ #ifdef LIBRARIES if (s->flags & SUFF_LIBRARY) { Dir_Concat(inLibs, s->searchPath); } #endif /* LIBRARIES */ Dir_Concat(s->searchPath, dirSearchPath); } else { Lst_Destroy(s->searchPath, Dir_Destroy); s->searchPath = Lst_Duplicate(dirSearchPath, Dir_CopyDir); } } Var_Set(".INCLUDES", ptr = Dir_MakeFlags("-I", inIncludes), VAR_GLOBAL, 0); free(ptr); Var_Set(".LIBS", ptr = Dir_MakeFlags("-L", inLibs), VAR_GLOBAL, 0); free(ptr); Lst_Destroy(inIncludes, Dir_Destroy); Lst_Destroy(inLibs, Dir_Destroy); Lst_Close(sufflist); } /*- *----------------------------------------------------------------------- * Suff_AddInclude -- * Add the given suffix as a type of file which gets included. * Called from the parse module when a .INCLUDES line is parsed. * The suffix must have already been defined. * * Input: * sname Name of the suffix to mark * * Results: * None. * * Side Effects: * The SUFF_INCLUDE bit is set in the suffix's flags field * *----------------------------------------------------------------------- */ void Suff_AddInclude(char *sname) { LstNode ln; Suff *s; ln = Lst_Find(sufflist, sname, SuffSuffHasNameP); if (ln != NULL) { s = (Suff *)Lst_Datum(ln); s->flags |= SUFF_INCLUDE; } } /*- *----------------------------------------------------------------------- * Suff_AddLib -- * Add the given suffix as a type of file which is a library. * Called from the parse module when parsing a .LIBS line. The * suffix must have been defined via .SUFFIXES before this is * called. * * Input: * sname Name of the suffix to mark * * Results: * None. * * Side Effects: * The SUFF_LIBRARY bit is set in the suffix's flags field * *----------------------------------------------------------------------- */ void Suff_AddLib(char *sname) { LstNode ln; Suff *s; ln = Lst_Find(sufflist, sname, SuffSuffHasNameP); if (ln != NULL) { s = (Suff *)Lst_Datum(ln); s->flags |= SUFF_LIBRARY; } } /********** Implicit Source Search Functions *********/ /*- *----------------------------------------------------------------------- * SuffAddSrc -- * Add a suffix as a Src structure to the given list with its parent * being the given Src structure. If the suffix is the null suffix, * the prefix is used unaltered as the file name in the Src structure. * * Input: * sp suffix for which to create a Src structure * lsp list and parent for the new Src * * Results: * always returns 0 * * Side Effects: * A Src structure is created and tacked onto the end of the list *----------------------------------------------------------------------- */ static int SuffAddSrc(void *sp, void *lsp) { Suff *s = (Suff *)sp; LstSrc *ls = (LstSrc *)lsp; Src *s2; /* new Src structure */ Src *targ; /* Target structure */ targ = ls->s; if ((s->flags & SUFF_NULL) && (*s->name != '\0')) { /* * If the suffix has been marked as the NULL suffix, also create a Src * structure for a file with no suffix attached. Two birds, and all * that... */ s2 = bmake_malloc(sizeof(Src)); s2->file = bmake_strdup(targ->pref); s2->pref = targ->pref; s2->parent = targ; s2->node = NULL; s2->suff = s; s->refCount++; s2->children = 0; targ->children += 1; (void)Lst_AtEnd(ls->l, s2); #ifdef DEBUG_SRC s2->cp = Lst_Init(FALSE); Lst_AtEnd(targ->cp, s2); fprintf(debug_file, "1 add %x %x to %x:", targ, s2, ls->l); Lst_ForEach(ls->l, PrintAddr, NULL); fprintf(debug_file, "\n"); #endif } s2 = bmake_malloc(sizeof(Src)); s2->file = str_concat(targ->pref, s->name, 0); s2->pref = targ->pref; s2->parent = targ; s2->node = NULL; s2->suff = s; s->refCount++; s2->children = 0; targ->children += 1; (void)Lst_AtEnd(ls->l, s2); #ifdef DEBUG_SRC s2->cp = Lst_Init(FALSE); Lst_AtEnd(targ->cp, s2); fprintf(debug_file, "2 add %x %x to %x:", targ, s2, ls->l); Lst_ForEach(ls->l, PrintAddr, NULL); fprintf(debug_file, "\n"); #endif return(0); } /*- *----------------------------------------------------------------------- * SuffAddLevel -- * Add all the children of targ as Src structures to the given list * * Input: * l list to which to add the new level * targ Src structure to use as the parent * * Results: * None * * Side Effects: * Lots of structures are created and added to the list *----------------------------------------------------------------------- */ static void SuffAddLevel(Lst l, Src *targ) { LstSrc ls; ls.s = targ; ls.l = l; Lst_ForEach(targ->suff->children, SuffAddSrc, &ls); } /*- *---------------------------------------------------------------------- * SuffRemoveSrc -- * Free all src structures in list that don't have a reference count * * Results: * Ture if an src was removed * * Side Effects: * The memory is free'd. *---------------------------------------------------------------------- */ static int SuffRemoveSrc(Lst l) { LstNode ln; Src *s; int t = 0; if (Lst_Open(l) == FAILURE) { return 0; } #ifdef DEBUG_SRC fprintf(debug_file, "cleaning %lx: ", (unsigned long) l); Lst_ForEach(l, PrintAddr, NULL); fprintf(debug_file, "\n"); #endif while ((ln = Lst_Next(l)) != NULL) { s = (Src *)Lst_Datum(ln); if (s->children == 0) { free(s->file); if (!s->parent) free(s->pref); else { #ifdef DEBUG_SRC LstNode ln = Lst_Member(s->parent->cp, s); if (ln != NULL) Lst_Remove(s->parent->cp, ln); #endif --s->parent->children; } #ifdef DEBUG_SRC fprintf(debug_file, "free: [l=%x] p=%x %d\n", l, s, s->children); Lst_Destroy(s->cp, NULL); #endif Lst_Remove(l, ln); free(s); t |= 1; Lst_Close(l); return TRUE; } #ifdef DEBUG_SRC else { fprintf(debug_file, "keep: [l=%x] p=%x %d: ", l, s, s->children); Lst_ForEach(s->cp, PrintAddr, NULL); fprintf(debug_file, "\n"); } #endif } Lst_Close(l); return t; } /*- *----------------------------------------------------------------------- * SuffFindThem -- * Find the first existing file/target in the list srcs * * Input: * srcs list of Src structures to search through * * Results: * The lowest structure in the chain of transformations * * Side Effects: * None *----------------------------------------------------------------------- */ static Src * SuffFindThem(Lst srcs, Lst slst) { Src *s; /* current Src */ Src *rs; /* returned Src */ char *ptr; rs = NULL; while (!Lst_IsEmpty (srcs)) { s = (Src *)Lst_DeQueue(srcs); if (DEBUG(SUFF)) { fprintf(debug_file, "\ttrying %s...", s->file); } /* * A file is considered to exist if either a node exists in the * graph for it or the file actually exists. */ if (Targ_FindNode(s->file, TARG_NOCREATE) != NULL) { #ifdef DEBUG_SRC fprintf(debug_file, "remove %x from %x\n", s, srcs); #endif rs = s; break; } if ((ptr = Dir_FindFile(s->file, s->suff->searchPath)) != NULL) { rs = s; #ifdef DEBUG_SRC fprintf(debug_file, "remove %x from %x\n", s, srcs); #endif free(ptr); break; } if (DEBUG(SUFF)) { fprintf(debug_file, "not there\n"); } SuffAddLevel(srcs, s); Lst_AtEnd(slst, s); } if (DEBUG(SUFF) && rs) { fprintf(debug_file, "got it\n"); } return (rs); } /*- *----------------------------------------------------------------------- * SuffFindCmds -- * See if any of the children of the target in the Src structure is * one from which the target can be transformed. If there is one, * a Src structure is put together for it and returned. * * Input: * targ Src structure to play with * * Results: * The Src structure of the "winning" child, or NULL if no such beast. * * Side Effects: * A Src structure may be allocated. * *----------------------------------------------------------------------- */ static Src * SuffFindCmds(Src *targ, Lst slst) { LstNode ln; /* General-purpose list node */ GNode *t, /* Target GNode */ *s; /* Source GNode */ int prefLen;/* The length of the defined prefix */ Suff *suff; /* Suffix on matching beastie */ Src *ret; /* Return value */ char *cp; t = targ->node; (void)Lst_Open(t->children); prefLen = strlen(targ->pref); for (;;) { ln = Lst_Next(t->children); if (ln == NULL) { Lst_Close(t->children); return NULL; } s = (GNode *)Lst_Datum(ln); if (s->type & OP_OPTIONAL && Lst_IsEmpty(t->commands)) { /* * We haven't looked to see if .OPTIONAL files exist yet, so * don't use one as the implicit source. * This allows us to use .OPTIONAL in .depend files so make won't * complain "don't know how to make xxx.h' when a dependent file * has been moved/deleted. */ continue; } cp = strrchr(s->name, '/'); if (cp == NULL) { cp = s->name; } else { cp++; } if (strncmp(cp, targ->pref, prefLen) != 0) continue; /* * The node matches the prefix ok, see if it has a known * suffix. */ ln = Lst_Find(sufflist, &cp[prefLen], SuffSuffHasNameP); if (ln == NULL) continue; /* * It even has a known suffix, see if there's a transformation * defined between the node's suffix and the target's suffix. * * XXX: Handle multi-stage transformations here, too. */ suff = (Suff *)Lst_Datum(ln); if (Lst_Member(suff->parents, targ->suff) != NULL) break; } /* * Hot Damn! Create a new Src structure to describe * this transformation (making sure to duplicate the * source node's name so Suff_FindDeps can free it * again (ick)), and return the new structure. */ ret = bmake_malloc(sizeof(Src)); ret->file = bmake_strdup(s->name); ret->pref = targ->pref; ret->suff = suff; suff->refCount++; ret->parent = targ; ret->node = s; ret->children = 0; targ->children += 1; #ifdef DEBUG_SRC ret->cp = Lst_Init(FALSE); fprintf(debug_file, "3 add %x %x\n", targ, ret); Lst_AtEnd(targ->cp, ret); #endif Lst_AtEnd(slst, ret); if (DEBUG(SUFF)) { fprintf(debug_file, "\tusing existing source %s\n", s->name); } return (ret); } /*- *----------------------------------------------------------------------- * SuffExpandChildren -- * Expand the names of any children of a given node that contain * variable invocations or file wildcards into actual targets. * * Input: * cln Child to examine * pgn Parent node being processed * * Results: * === 0 (continue) * * Side Effects: * The expanded node is removed from the parent's list of children, * and the parent's unmade counter is decremented, but other nodes * may be added. * *----------------------------------------------------------------------- */ static void SuffExpandChildren(LstNode cln, GNode *pgn) { GNode *cgn = (GNode *)Lst_Datum(cln); GNode *gn; /* New source 8) */ char *cp; /* Expanded value */ if (!Lst_IsEmpty(cgn->order_pred) || !Lst_IsEmpty(cgn->order_succ)) /* It is all too hard to process the result of .ORDER */ return; if (cgn->type & OP_WAIT) /* Ignore these (& OP_PHONY ?) */ return; /* * First do variable expansion -- this takes precedence over * wildcard expansion. If the result contains wildcards, they'll be gotten * to later since the resulting words are tacked on to the end of * the children list. */ if (strchr(cgn->name, '$') == NULL) { SuffExpandWildcards(cln, pgn); return; } if (DEBUG(SUFF)) { fprintf(debug_file, "Expanding \"%s\"...", cgn->name); } cp = Var_Subst(NULL, cgn->name, pgn, TRUE); if (cp != NULL) { Lst members = Lst_Init(FALSE); if (cgn->type & OP_ARCHV) { /* * Node was an archive(member) target, so we want to call * on the Arch module to find the nodes for us, expanding * variables in the parent's context. */ char *sacrifice = cp; (void)Arch_ParseArchive(&sacrifice, members, pgn); } else { /* * Break the result into a vector of strings whose nodes * we can find, then add those nodes to the members list. * Unfortunately, we can't use brk_string b/c it * doesn't understand about variable specifications with * spaces in them... */ char *start; char *initcp = cp; /* For freeing... */ for (start = cp; *start == ' ' || *start == '\t'; start++) continue; for (cp = start; *cp != '\0'; cp++) { if (*cp == ' ' || *cp == '\t') { /* * White-space -- terminate element, find the node, * add it, skip any further spaces. */ *cp++ = '\0'; gn = Targ_FindNode(start, TARG_CREATE); (void)Lst_AtEnd(members, gn); while (*cp == ' ' || *cp == '\t') { cp++; } /* * Adjust cp for increment at start of loop, but * set start to first non-space. */ start = cp--; } else if (*cp == '$') { /* * Start of a variable spec -- contact variable module * to find the end so we can skip over it. */ char *junk; int len; void *freeIt; junk = Var_Parse(cp, pgn, TRUE, &len, &freeIt); if (junk != var_Error) { cp += len - 1; } if (freeIt) free(freeIt); } else if (*cp == '\\' && *cp != '\0') { /* * Escaped something -- skip over it */ cp++; } } if (cp != start) { /* * Stuff left over -- add it to the list too */ gn = Targ_FindNode(start, TARG_CREATE); (void)Lst_AtEnd(members, gn); } /* * Point cp back at the beginning again so the variable value * can be freed. */ cp = initcp; } /* * Add all elements of the members list to the parent node. */ while(!Lst_IsEmpty(members)) { gn = (GNode *)Lst_DeQueue(members); if (DEBUG(SUFF)) { fprintf(debug_file, "%s...", gn->name); } /* Add gn to the parents child list before the original child */ (void)Lst_InsertBefore(pgn->children, cln, gn); (void)Lst_AtEnd(gn->parents, pgn); pgn->unmade++; /* Expand wildcards on new node */ SuffExpandWildcards(Lst_Prev(cln), pgn); } Lst_Destroy(members, NULL); /* * Free the result */ free(cp); } if (DEBUG(SUFF)) { fprintf(debug_file, "\n"); } /* * Now the source is expanded, remove it from the list of children to * keep it from being processed. */ pgn->unmade--; Lst_Remove(pgn->children, cln); Lst_Remove(cgn->parents, Lst_Member(cgn->parents, pgn)); } static void SuffExpandWildcards(LstNode cln, GNode *pgn) { GNode *cgn = (GNode *)Lst_Datum(cln); GNode *gn; /* New source 8) */ char *cp; /* Expanded value */ Lst explist; /* List of expansions */ if (!Dir_HasWildcards(cgn->name)) return; /* * Expand the word along the chosen path */ explist = Lst_Init(FALSE); Dir_Expand(cgn->name, Suff_FindPath(cgn), explist); while (!Lst_IsEmpty(explist)) { /* * Fetch next expansion off the list and find its GNode */ cp = (char *)Lst_DeQueue(explist); if (DEBUG(SUFF)) { fprintf(debug_file, "%s...", cp); } gn = Targ_FindNode(cp, TARG_CREATE); /* Add gn to the parents child list before the original child */ (void)Lst_InsertBefore(pgn->children, cln, gn); (void)Lst_AtEnd(gn->parents, pgn); pgn->unmade++; } /* * Nuke what's left of the list */ Lst_Destroy(explist, NULL); if (DEBUG(SUFF)) { fprintf(debug_file, "\n"); } /* * Now the source is expanded, remove it from the list of children to * keep it from being processed. */ pgn->unmade--; Lst_Remove(pgn->children, cln); Lst_Remove(cgn->parents, Lst_Member(cgn->parents, pgn)); } /*- *----------------------------------------------------------------------- * Suff_FindPath -- * Find a path along which to expand the node. * * If the word has a known suffix, use that path. * If it has no known suffix, use the default system search path. * * Input: * gn Node being examined * * Results: * The appropriate path to search for the GNode. * * Side Effects: * XXX: We could set the suffix here so that we don't have to scan * again. * *----------------------------------------------------------------------- */ Lst Suff_FindPath(GNode* gn) { Suff *suff = gn->suffix; if (suff == NULL) { SuffixCmpData sd; /* Search string data */ LstNode ln; sd.len = strlen(gn->name); sd.ename = gn->name + sd.len; ln = Lst_Find(sufflist, &sd, SuffSuffIsSuffixP); if (DEBUG(SUFF)) { fprintf(debug_file, "Wildcard expanding \"%s\"...", gn->name); } if (ln != NULL) suff = (Suff *)Lst_Datum(ln); /* XXX: Here we can save the suffix so we don't have to do this again */ } if (suff != NULL) { if (DEBUG(SUFF)) { fprintf(debug_file, "suffix is \"%s\"...", suff->name); } return suff->searchPath; } else { /* * Use default search path */ return dirSearchPath; } } /*- *----------------------------------------------------------------------- * SuffApplyTransform -- * Apply a transformation rule, given the source and target nodes * and suffixes. * * Input: * tGn Target node * sGn Source node * t Target suffix * s Source suffix * * Results: * TRUE if successful, FALSE if not. * * Side Effects: * The source and target are linked and the commands from the * transformation are added to the target node's commands list. * All attributes but OP_DEPMASK and OP_TRANSFORM are applied * to the target. The target also inherits all the sources for * the transformation rule. * *----------------------------------------------------------------------- */ static Boolean SuffApplyTransform(GNode *tGn, GNode *sGn, Suff *t, Suff *s) { LstNode ln, nln; /* General node */ char *tname; /* Name of transformation rule */ GNode *gn; /* Node for same */ /* * Form the proper links between the target and source. */ (void)Lst_AtEnd(tGn->children, sGn); (void)Lst_AtEnd(sGn->parents, tGn); tGn->unmade += 1; /* * Locate the transformation rule itself */ tname = str_concat(s->name, t->name, 0); ln = Lst_Find(transforms, tname, SuffGNHasNameP); free(tname); if (ln == NULL) { /* * Not really such a transformation rule (can happen when we're * called to link an OP_MEMBER and OP_ARCHV node), so return * FALSE. */ return(FALSE); } gn = (GNode *)Lst_Datum(ln); if (DEBUG(SUFF)) { fprintf(debug_file, "\tapplying %s -> %s to \"%s\"\n", s->name, t->name, tGn->name); } /* * Record last child for expansion purposes */ ln = Lst_Last(tGn->children); /* * Pass the buck to Make_HandleUse to apply the rule */ (void)Make_HandleUse(gn, tGn); /* * Deal with wildcards and variables in any acquired sources */ for (ln = Lst_Succ(ln); ln != NULL; ln = nln) { nln = Lst_Succ(ln); SuffExpandChildren(ln, tGn); } /* * Keep track of another parent to which this beast is transformed so * the .IMPSRC variable can be set correctly for the parent. */ (void)Lst_AtEnd(sGn->iParents, tGn); return(TRUE); } /*- *----------------------------------------------------------------------- * SuffFindArchiveDeps -- * Locate dependencies for an OP_ARCHV node. * * Input: * gn Node for which to locate dependencies * * Results: * None * * Side Effects: * Same as Suff_FindDeps * *----------------------------------------------------------------------- */ static void SuffFindArchiveDeps(GNode *gn, Lst slst) { char *eoarch; /* End of archive portion */ char *eoname; /* End of member portion */ GNode *mem; /* Node for member */ static const char *copy[] = { /* Variables to be copied from the member node */ TARGET, /* Must be first */ PREFIX, /* Must be second */ }; int i; /* Index into copy and vals */ Suff *ms; /* Suffix descriptor for member */ char *name; /* Start of member's name */ /* * The node is an archive(member) pair. so we must find a * suffix for both of them. */ eoarch = strchr(gn->name, '('); eoname = strchr(eoarch, ')'); *eoname = '\0'; /* Nuke parentheses during suffix search */ *eoarch = '\0'; /* So a suffix can be found */ name = eoarch + 1; /* * To simplify things, call Suff_FindDeps recursively on the member now, * so we can simply compare the member's .PREFIX and .TARGET variables * to locate its suffix. This allows us to figure out the suffix to * use for the archive without having to do a quadratic search over the * suffix list, backtracking for each one... */ mem = Targ_FindNode(name, TARG_CREATE); SuffFindDeps(mem, slst); /* * Create the link between the two nodes right off */ (void)Lst_AtEnd(gn->children, mem); (void)Lst_AtEnd(mem->parents, gn); gn->unmade += 1; /* * Copy in the variables from the member node to this one. */ for (i = (sizeof(copy)/sizeof(copy[0]))-1; i >= 0; i--) { char *p1; Var_Set(copy[i], Var_Value(copy[i], mem, &p1), gn, 0); if (p1) free(p1); } ms = mem->suffix; if (ms == NULL) { /* * Didn't know what it was -- use .NULL suffix if not in make mode */ if (DEBUG(SUFF)) { fprintf(debug_file, "using null suffix\n"); } ms = suffNull; } /* * Set the other two local variables required for this target. */ Var_Set(MEMBER, name, gn, 0); Var_Set(ARCHIVE, gn->name, gn, 0); if (ms != NULL) { /* * Member has a known suffix, so look for a transformation rule from * it to a possible suffix of the archive. Rather than searching * through the entire list, we just look at suffixes to which the * member's suffix may be transformed... */ LstNode ln; SuffixCmpData sd; /* Search string data */ /* * Use first matching suffix... */ sd.len = eoarch - gn->name; sd.ename = eoarch; ln = Lst_Find(ms->parents, &sd, SuffSuffIsSuffixP); if (ln != NULL) { /* * Got one -- apply it */ if (!SuffApplyTransform(gn, mem, (Suff *)Lst_Datum(ln), ms) && DEBUG(SUFF)) { fprintf(debug_file, "\tNo transformation from %s -> %s\n", ms->name, ((Suff *)Lst_Datum(ln))->name); } } } /* * Replace the opening and closing parens now we've no need of the separate * pieces. */ *eoarch = '('; *eoname = ')'; /* * Pretend gn appeared to the left of a dependency operator so * the user needn't provide a transformation from the member to the * archive. */ if (OP_NOP(gn->type)) { gn->type |= OP_DEPENDS; } /* * Flag the member as such so we remember to look in the archive for * its modification time. */ mem->type |= OP_MEMBER; } /*- *----------------------------------------------------------------------- * SuffFindNormalDeps -- * Locate implicit dependencies for regular targets. * * Input: * gn Node for which to find sources * * Results: * None. * * Side Effects: * Same as Suff_FindDeps... * *----------------------------------------------------------------------- */ static void SuffFindNormalDeps(GNode *gn, Lst slst) { char *eoname; /* End of name */ char *sopref; /* Start of prefix */ LstNode ln, nln; /* Next suffix node to check */ Lst srcs; /* List of sources at which to look */ Lst targs; /* List of targets to which things can be * transformed. They all have the same file, * but different suff and pref fields */ Src *bottom; /* Start of found transformation path */ Src *src; /* General Src pointer */ char *pref; /* Prefix to use */ Src *targ; /* General Src target pointer */ SuffixCmpData sd; /* Search string data */ sd.len = strlen(gn->name); sd.ename = eoname = gn->name + sd.len; sopref = gn->name; /* * Begin at the beginning... */ ln = Lst_First(sufflist); srcs = Lst_Init(FALSE); targs = Lst_Init(FALSE); /* * We're caught in a catch-22 here. On the one hand, we want to use any * transformation implied by the target's sources, but we can't examine * the sources until we've expanded any variables/wildcards they may hold, * and we can't do that until we've set up the target's local variables * and we can't do that until we know what the proper suffix for the * target is (in case there are two suffixes one of which is a suffix of * the other) and we can't know that until we've found its implied * source, which we may not want to use if there's an existing source * that implies a different transformation. * * In an attempt to get around this, which may not work all the time, * but should work most of the time, we look for implied sources first, * checking transformations to all possible suffixes of the target, * use what we find to set the target's local variables, expand the * children, then look for any overriding transformations they imply. * Should we find one, we discard the one we found before. */ bottom = NULL; targ = NULL; if (!(gn->type & OP_PHONY)) { while (ln != NULL) { /* * Look for next possible suffix... */ ln = Lst_FindFrom(sufflist, ln, &sd, SuffSuffIsSuffixP); if (ln != NULL) { int prefLen; /* Length of the prefix */ /* * Allocate a Src structure to which things can be transformed */ targ = bmake_malloc(sizeof(Src)); targ->file = bmake_strdup(gn->name); targ->suff = (Suff *)Lst_Datum(ln); targ->suff->refCount++; targ->node = gn; targ->parent = NULL; targ->children = 0; #ifdef DEBUG_SRC targ->cp = Lst_Init(FALSE); #endif /* * Allocate room for the prefix, whose end is found by * subtracting the length of the suffix from * the end of the name. */ prefLen = (eoname - targ->suff->nameLen) - sopref; targ->pref = bmake_malloc(prefLen + 1); memcpy(targ->pref, sopref, prefLen); targ->pref[prefLen] = '\0'; /* * Add nodes from which the target can be made */ SuffAddLevel(srcs, targ); /* * Record the target so we can nuke it */ (void)Lst_AtEnd(targs, targ); /* * Search from this suffix's successor... */ ln = Lst_Succ(ln); } } /* * Handle target of unknown suffix... */ if (Lst_IsEmpty(targs) && suffNull != NULL) { if (DEBUG(SUFF)) { fprintf(debug_file, "\tNo known suffix on %s. Using .NULL suffix\n", gn->name); } targ = bmake_malloc(sizeof(Src)); targ->file = bmake_strdup(gn->name); targ->suff = suffNull; targ->suff->refCount++; targ->node = gn; targ->parent = NULL; targ->children = 0; targ->pref = bmake_strdup(sopref); #ifdef DEBUG_SRC targ->cp = Lst_Init(FALSE); #endif /* * Only use the default suffix rules if we don't have commands * defined for this gnode; traditional make programs used to * not define suffix rules if the gnode had children but we * don't do this anymore. */ if (Lst_IsEmpty(gn->commands)) SuffAddLevel(srcs, targ); else { if (DEBUG(SUFF)) fprintf(debug_file, "not "); } if (DEBUG(SUFF)) fprintf(debug_file, "adding suffix rules\n"); (void)Lst_AtEnd(targs, targ); } /* * Using the list of possible sources built up from the target * suffix(es), try and find an existing file/target that matches. */ bottom = SuffFindThem(srcs, slst); if (bottom == NULL) { /* * No known transformations -- use the first suffix found * for setting the local variables. */ if (!Lst_IsEmpty(targs)) { targ = (Src *)Lst_Datum(Lst_First(targs)); } else { targ = NULL; } } else { /* * Work up the transformation path to find the suffix of the * target to which the transformation was made. */ for (targ = bottom; targ->parent != NULL; targ = targ->parent) continue; } } Var_Set(TARGET, gn->path ? gn->path : gn->name, gn, 0); pref = (targ != NULL) ? targ->pref : gn->name; Var_Set(PREFIX, pref, gn, 0); /* * Now we've got the important local variables set, expand any sources * that still contain variables or wildcards in their names. */ for (ln = Lst_First(gn->children); ln != NULL; ln = nln) { nln = Lst_Succ(ln); SuffExpandChildren(ln, gn); } if (targ == NULL) { if (DEBUG(SUFF)) { fprintf(debug_file, "\tNo valid suffix on %s\n", gn->name); } sfnd_abort: /* * Deal with finding the thing on the default search path. We * always do that, not only if the node is only a source (not * on the lhs of a dependency operator or [XXX] it has neither * children or commands) as the old pmake did. */ if ((gn->type & (OP_PHONY|OP_NOPATH)) == 0) { free(gn->path); gn->path = Dir_FindFile(gn->name, (targ == NULL ? dirSearchPath : targ->suff->searchPath)); if (gn->path != NULL) { char *ptr; Var_Set(TARGET, gn->path, gn, 0); if (targ != NULL) { /* * Suffix known for the thing -- trim the suffix off * the path to form the proper .PREFIX variable. */ int savep = strlen(gn->path) - targ->suff->nameLen; char savec; if (gn->suffix) gn->suffix->refCount--; gn->suffix = targ->suff; gn->suffix->refCount++; savec = gn->path[savep]; gn->path[savep] = '\0'; if ((ptr = strrchr(gn->path, '/')) != NULL) ptr++; else ptr = gn->path; Var_Set(PREFIX, ptr, gn, 0); gn->path[savep] = savec; } else { /* * The .PREFIX gets the full path if the target has * no known suffix. */ if (gn->suffix) gn->suffix->refCount--; gn->suffix = NULL; if ((ptr = strrchr(gn->path, '/')) != NULL) ptr++; else ptr = gn->path; Var_Set(PREFIX, ptr, gn, 0); } } } goto sfnd_return; } /* * If the suffix indicates that the target is a library, mark that in * the node's type field. */ if (targ->suff->flags & SUFF_LIBRARY) { gn->type |= OP_LIB; } /* * Check for overriding transformation rule implied by sources */ if (!Lst_IsEmpty(gn->children)) { src = SuffFindCmds(targ, slst); if (src != NULL) { /* * Free up all the Src structures in the transformation path * up to, but not including, the parent node. */ while (bottom && bottom->parent != NULL) { if (Lst_Member(slst, bottom) == NULL) { Lst_AtEnd(slst, bottom); } bottom = bottom->parent; } bottom = src; } } if (bottom == NULL) { /* * No idea from where it can come -- return now. */ goto sfnd_abort; } /* * We now have a list of Src structures headed by 'bottom' and linked via * their 'parent' pointers. What we do next is create links between * source and target nodes (which may or may not have been created) * and set the necessary local variables in each target. The * commands for each target are set from the commands of the * transformation rule used to get from the src suffix to the targ * suffix. Note that this causes the commands list of the original * node, gn, to be replaced by the commands of the final * transformation rule. Also, the unmade field of gn is incremented. * Etc. */ if (bottom->node == NULL) { bottom->node = Targ_FindNode(bottom->file, TARG_CREATE); } for (src = bottom; src->parent != NULL; src = src->parent) { targ = src->parent; if (src->node->suffix) src->node->suffix->refCount--; src->node->suffix = src->suff; src->node->suffix->refCount++; if (targ->node == NULL) { targ->node = Targ_FindNode(targ->file, TARG_CREATE); } SuffApplyTransform(targ->node, src->node, targ->suff, src->suff); if (targ->node != gn) { /* * Finish off the dependency-search process for any nodes * between bottom and gn (no point in questing around the * filesystem for their implicit source when it's already * known). Note that the node can't have any sources that * need expanding, since SuffFindThem will stop on an existing * node, so all we need to do is set the standard and System V * variables. */ targ->node->type |= OP_DEPS_FOUND; Var_Set(PREFIX, targ->pref, targ->node, 0); Var_Set(TARGET, targ->node->name, targ->node, 0); } } if (gn->suffix) gn->suffix->refCount--; gn->suffix = src->suff; gn->suffix->refCount++; /* * Nuke the transformation path and the Src structures left over in the * two lists. */ sfnd_return: if (bottom) if (Lst_Member(slst, bottom) == NULL) Lst_AtEnd(slst, bottom); while (SuffRemoveSrc(srcs) || SuffRemoveSrc(targs)) continue; Lst_Concat(slst, srcs, LST_CONCLINK); Lst_Concat(slst, targs, LST_CONCLINK); } /*- *----------------------------------------------------------------------- * Suff_FindDeps -- * Find implicit sources for the target described by the graph node * gn * * Results: * Nothing. * * Side Effects: * Nodes are added to the graph below the passed-in node. The nodes * are marked to have their IMPSRC variable filled in. The * PREFIX variable is set for the given node and all its * implied children. * * Notes: * The path found by this target is the shortest path in the * transformation graph, which may pass through non-existent targets, * to an existing target. The search continues on all paths from the * root suffix until a file is found. I.e. if there's a path * .o -> .c -> .l -> .l,v from the root and the .l,v file exists but * the .c and .l files don't, the search will branch out in * all directions from .o and again from all the nodes on the * next level until the .l,v node is encountered. * *----------------------------------------------------------------------- */ void Suff_FindDeps(GNode *gn) { SuffFindDeps(gn, srclist); while (SuffRemoveSrc(srclist)) continue; } /* * Input: * gn node we're dealing with * */ static void SuffFindDeps(GNode *gn, Lst slst) { if (gn->type & OP_DEPS_FOUND) { /* * If dependencies already found, no need to do it again... */ return; } else { gn->type |= OP_DEPS_FOUND; } /* * Make sure we have these set, may get revised below. */ Var_Set(TARGET, gn->path ? gn->path : gn->name, gn, 0); Var_Set(PREFIX, gn->name, gn, 0); if (DEBUG(SUFF)) { fprintf(debug_file, "SuffFindDeps (%s)\n", gn->name); } if (gn->type & OP_ARCHV) { SuffFindArchiveDeps(gn, slst); } else if (gn->type & OP_LIB) { /* * If the node is a library, it is the arch module's job to find it * and set the TARGET variable accordingly. We merely provide the * search path, assuming all libraries end in ".a" (if the suffix * hasn't been defined, there's nothing we can do for it, so we just * set the TARGET variable to the node's name in order to give it a * value). */ LstNode ln; Suff *s; ln = Lst_Find(sufflist, LIBSUFF, SuffSuffHasNameP); if (gn->suffix) gn->suffix->refCount--; if (ln != NULL) { gn->suffix = s = (Suff *)Lst_Datum(ln); gn->suffix->refCount++; Arch_FindLib(gn, s->searchPath); } else { gn->suffix = NULL; Var_Set(TARGET, gn->name, gn, 0); } /* * Because a library (-lfoo) target doesn't follow the standard * filesystem conventions, we don't set the regular variables for * the thing. .PREFIX is simply made empty... */ Var_Set(PREFIX, "", gn, 0); } else { SuffFindNormalDeps(gn, slst); } } /*- *----------------------------------------------------------------------- * Suff_SetNull -- * Define which suffix is the null suffix. * * Input: * name Name of null suffix * * Results: * None. * * Side Effects: * 'suffNull' is altered. * * Notes: * Need to handle the changing of the null suffix gracefully so the * old transformation rules don't just go away. * *----------------------------------------------------------------------- */ void Suff_SetNull(char *name) { Suff *s; LstNode ln; ln = Lst_Find(sufflist, name, SuffSuffHasNameP); if (ln != NULL) { s = (Suff *)Lst_Datum(ln); if (suffNull != NULL) { suffNull->flags &= ~SUFF_NULL; } s->flags |= SUFF_NULL; /* * XXX: Here's where the transformation mangling would take place */ suffNull = s; } else { Parse_Error(PARSE_WARNING, "Desired null suffix %s not defined.", name); } } /*- *----------------------------------------------------------------------- * Suff_Init -- * Initialize suffixes module * * Results: * None * * Side Effects: * Many *----------------------------------------------------------------------- */ void Suff_Init(void) { sufflist = Lst_Init(FALSE); #ifdef CLEANUP suffClean = Lst_Init(FALSE); #endif srclist = Lst_Init(FALSE); transforms = Lst_Init(FALSE); sNum = 0; /* * Create null suffix for single-suffix rules (POSIX). The thing doesn't * actually go on the suffix list or everyone will think that's its * suffix. */ emptySuff = suffNull = bmake_malloc(sizeof(Suff)); suffNull->name = bmake_strdup(""); suffNull->nameLen = 0; suffNull->searchPath = Lst_Init(FALSE); Dir_Concat(suffNull->searchPath, dirSearchPath); suffNull->children = Lst_Init(FALSE); suffNull->parents = Lst_Init(FALSE); suffNull->ref = Lst_Init(FALSE); suffNull->sNum = sNum++; suffNull->flags = SUFF_NULL; suffNull->refCount = 1; } /*- *---------------------------------------------------------------------- * Suff_End -- * Cleanup the this module * * Results: * None * * Side Effects: * The memory is free'd. *---------------------------------------------------------------------- */ void Suff_End(void) { #ifdef CLEANUP Lst_Destroy(sufflist, SuffFree); Lst_Destroy(suffClean, SuffFree); if (suffNull) SuffFree(suffNull); Lst_Destroy(srclist, NULL); Lst_Destroy(transforms, NULL); #endif } /********************* DEBUGGING FUNCTIONS **********************/ static int SuffPrintName(void *s, void *dummy) { fprintf(debug_file, "%s ", ((Suff *)s)->name); return (dummy ? 0 : 0); } static int SuffPrintSuff(void *sp, void *dummy) { Suff *s = (Suff *)sp; int flags; int flag; fprintf(debug_file, "# `%s' [%d] ", s->name, s->refCount); flags = s->flags; if (flags) { fputs(" (", debug_file); while (flags) { flag = 1 << (ffs(flags) - 1); flags &= ~flag; switch (flag) { case SUFF_NULL: fprintf(debug_file, "NULL"); break; case SUFF_INCLUDE: fprintf(debug_file, "INCLUDE"); break; case SUFF_LIBRARY: fprintf(debug_file, "LIBRARY"); break; } fputc(flags ? '|' : ')', debug_file); } } fputc('\n', debug_file); fprintf(debug_file, "#\tTo: "); Lst_ForEach(s->parents, SuffPrintName, NULL); fputc('\n', debug_file); fprintf(debug_file, "#\tFrom: "); Lst_ForEach(s->children, SuffPrintName, NULL); fputc('\n', debug_file); fprintf(debug_file, "#\tSearch Path: "); Dir_PrintPath(s->searchPath); fputc('\n', debug_file); return (dummy ? 0 : 0); } static int SuffPrintTrans(void *tp, void *dummy) { GNode *t = (GNode *)tp; fprintf(debug_file, "%-16s: ", t->name); Targ_PrintType(t->type); fputc('\n', debug_file); Lst_ForEach(t->commands, Targ_PrintCmd, NULL); fputc('\n', debug_file); return(dummy ? 0 : 0); } void Suff_PrintAll(void) { fprintf(debug_file, "#*** Suffixes:\n"); Lst_ForEach(sufflist, SuffPrintSuff, NULL); fprintf(debug_file, "#*** Transformations:\n"); Lst_ForEach(transforms, SuffPrintTrans, NULL); }
{ "content_hash": "2e0a025302dd4249096201a8c5afa1f6", "timestamp": "", "source": "github", "line_count": 2655, "max_line_length": 85, "avg_line_length": 26.931073446327684, "alnum_prop": 0.5708092081340382, "repo_name": "dplbsd/soc2013", "id": "d4f0eb183fc7d336a37c0295fa15eb19dbacd03b", "size": "71502", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "head/contrib/bmake/suff.c", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "AGS Script", "bytes": "62471" }, { "name": "Assembly", "bytes": "4478661" }, { "name": "Awk", "bytes": "278525" }, { "name": "Batchfile", "bytes": "20417" }, { "name": "C", "bytes": "383420305" }, { "name": "C++", "bytes": "72796771" }, { "name": "CSS", "bytes": "109748" }, { "name": "ChucK", "bytes": "39" }, { "name": "D", "bytes": "3784" }, { "name": "DIGITAL Command Language", "bytes": "10640" }, { "name": "DTrace", "bytes": "2311027" }, { "name": "Emacs Lisp", "bytes": "65902" }, { "name": "EmberScript", "bytes": "286" }, { "name": "Forth", "bytes": "184405" }, { "name": "GAP", "bytes": "72156" }, { "name": "Groff", "bytes": "32248806" }, { "name": "HTML", "bytes": "6749816" }, { "name": "IGOR Pro", "bytes": "6301" }, { "name": "Java", "bytes": "112547" }, { "name": "KRL", "bytes": "4950" }, { "name": "Lex", "bytes": "398817" }, { "name": "Limbo", "bytes": "3583" }, { "name": "Logos", "bytes": "187900" }, { "name": "Makefile", "bytes": "3551839" }, { "name": "Mathematica", "bytes": "9556" }, { "name": "Max", "bytes": "4178" }, { "name": "Module Management System", "bytes": "817" }, { "name": "NSIS", "bytes": "3383" }, { "name": "Objective-C", "bytes": "836351" }, { "name": "PHP", "bytes": "6649" }, { "name": "Perl", "bytes": "5530761" }, { "name": "Perl6", "bytes": "41802" }, { "name": "PostScript", "bytes": "140088" }, { "name": "Prolog", "bytes": "29514" }, { "name": "Protocol Buffer", "bytes": "61933" }, { "name": "Python", "bytes": "299247" }, { "name": "R", "bytes": "764" }, { "name": "Rebol", "bytes": "738" }, { "name": "Ruby", "bytes": "45958" }, { "name": "Scilab", "bytes": "197" }, { "name": "Shell", "bytes": "10501540" }, { "name": "SourcePawn", "bytes": "463194" }, { "name": "SuperCollider", "bytes": "80208" }, { "name": "Tcl", "bytes": "80913" }, { "name": "TeX", "bytes": "719821" }, { "name": "VimL", "bytes": "22201" }, { "name": "XS", "bytes": "25451" }, { "name": "XSLT", "bytes": "31488" }, { "name": "Yacc", "bytes": "1857830" } ], "symlink_target": "" }
import fetch from 'node-fetch'; import Env from 'require-env'; import addDays from './addDays'; const apiURL = `https://api.darksky.net/forecast/${Env.require('DARKSKY_API_KEY')}/`; async function getWeatherToday(geocode) { const response = await fetch(`${apiURL}${geocode.latitude},${geocode.longitude}`); // eslint-disable-line const weatherData = await response.json(); return weatherData; } async function getWeatherTomorrow(geocode) { const tomorrow = addDays(1); const response = await fetch(`${apiURL}${geocode.latitude},${geocode.longitude},${parseInt(tomorrow.getTime() / 1000, 10)}`); // eslint-disable-line const weatherData = await response.json(); return weatherData; } module.exports = { getWeatherToday, getWeatherTomorrow };
{ "content_hash": "04ab8d9b3f8cd317c5cccd43331250c8", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 152, "avg_line_length": 35.91304347826087, "alnum_prop": 0.6707021791767555, "repo_name": "elicaio/elica-weather", "id": "38430aaef5d8dc7559f054235485728b5f392ad8", "size": "826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/weather/utils/getWeather.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "16749" }, { "name": "Standard ML", "bytes": "1067" } ], "symlink_target": "" }
[![Open Source Love](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://github.com/ellerbrock/open-source-badges/) [<img align="right" src="https://firstcontributions.herokuapp.com/badge.svg">](https://firstcontributions.herokuapp.com) [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT) # hello-world Just my first repository on GitHub Will use Python on this project
{ "content_hash": "27604f6fe4c9ae2a0a0f060d9a132308", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 129, "avg_line_length": 62.857142857142854, "alnum_prop": 0.7613636363636364, "repo_name": "rafaelscnunes/hello-world", "id": "d3cb2179a247333867957ee990cff23f768e1d96", "size": "440", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imageView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/bird"/> </LinearLayout>
{ "content_hash": "21066b1026798a150a15c6d8fb869156", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 72, "avg_line_length": 34.916666666666664, "alnum_prop": 0.684964200477327, "repo_name": "IOT-410c/IOT-DB410c-Course-2", "id": "d55d435867e237a3d4f1d9c8725762c3c1d1ae92", "size": "419", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Modules/Module_8_Calit_Bird/app/src/main/res/layout/coordinate.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "8815" }, { "name": "Java", "bytes": "65981" } ], "symlink_target": "" }
import socket import sys # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = sys.argv[1] # Bind the socket to the port server_address = ('localhost', int(port)) print sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) raw_input("click any key to shutdown...")
{ "content_hash": "3f8a63759a210c3206d9e61382d4370c", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 62, "avg_line_length": 23.642857142857142, "alnum_prop": 0.7250755287009063, "repo_name": "radiovisual/zaport", "id": "7b8e04ec404065223449c849ca013172d2b36418", "size": "331", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/bindudp.py", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4012" }, { "name": "Python", "bytes": "331" } ], "symlink_target": "" }
package com.twitter.scalding import com.twitter.algebird.Semigroup object ExecutionUtil { /** * Generate a list of executions from a date range * * @param duration Duration to split daterange * @param fn Function to run a execution given a date range * @return Sequence of Executions per Day */ def executionsFromDates[T](duration: Duration)(fn: DateRange => Execution[T])(implicit dr: DateRange): Seq[Execution[T]] = dr.each(duration).map(fn).toSeq /** * Split a DateRange and allow for max parallel running of executions * * @param duration Duration to split daterange * @param parallelism How many jobs to run in parallel * @param fn Function to run a execution given a date range * @return Seq of Dates split by Duration with corresponding execution result */ def runDatesWithParallelism[T](duration: Duration, parallelism: Int = 1)(fn: DateRange => Execution[T])(implicit dr: DateRange): Execution[Seq[(DateRange, T)]] = { val dates = dr.each(duration).toSeq Execution.withParallelism(dates.map(fn), parallelism).map(e => dates.zip(e)) } /** * Split a DateRange and allow for max parallel running of executions * * @param duration Duration to split daterange * @param parallelism How many jobs to run in parallel * @param fn Function to run a execution given a date range * @return Execution of Sequences */ def runDateRangeWithParallelism[T](duration: Duration, parallelism: Int = 1)(fn: DateRange => Execution[T])(implicit dr: DateRange): Execution[Seq[T]] = runDatesWithParallelism(duration, parallelism)(fn).map(_.map{ case (_, t) => t }) /** * Same as runDateRangeWithParallelism, but sums the sequence * of values after running. This is useful when you want to do a * calculation in parallel over many durations and join the results * together. * * For example, a common use case is when T is * a TypedPipe[U] and you want to independently compute * the pipes on each day and union them into a * single TypedPipe at the end. * * Another possible use case would be if the executions were created by * summing intermediate monoids (e.g. T was a Map[String,HLL] since * algebird supports monoids for maps and hll) and you wanted to do a * final aggregation of the Monoids computed for each duration. */ def runDateRangeWithParallelismSum[T](duration: Duration, parallelism: Int = 1)(fn: DateRange => Execution[T])(implicit dr: DateRange, semigroup: Semigroup[T]): Execution[T] = { require(dr.each(duration).nonEmpty, "Date Range can not be empty") runDateRangeWithParallelism(duration, parallelism)(fn)(dr) .map(_.reduceLeft[T]{ case (l, r) => Semigroup.plus(l, r) }) } }
{ "content_hash": "3cc650a830de940a71b4e3a57e543e53", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 179, "avg_line_length": 43.523809523809526, "alnum_prop": 0.7100656455142232, "repo_name": "tresata/scalding", "id": "2ce63102a4700a6a74e3d73b36fe6f3818dbb51e", "size": "2742", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "scalding-core/src/main/scala/com/twitter/scalding/ExecutionUtil.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "105138" }, { "name": "Ruby", "bytes": "60597" }, { "name": "Scala", "bytes": "2157777" }, { "name": "Shell", "bytes": "30779" }, { "name": "Thrift", "bytes": "17348" } ], "symlink_target": "" }
// Copyright 2015 Patrick Putnam // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ADJACENCY_MATRIX_H_ #define ADJACENCY_MATRIX_H_ #include "page_manager.h" #include <ostream> /*********************************************************** * * PAGE LAYOUT: * ________________________________________________ *| Free Column bit vector ( COLUMN_HEADER_BLOCKS )| * ------------------------------------------------ *| Free Rows bit vector ( ROW_HEADER_BLOCKS ) | *| | * ------------------------------------------------ *| DATA (BLOCK_COUNT - x - y ) | * ------------------------------------------------ *| PADDING | *|________________________________________________| * * BLOCK_COUNT >= COLUMN_HEADER_BLOCKS (x) + ROW_HEADER_BLOCKS (y) + NODE_PER_BLOCK * x * y * ***********************************************************/ class adjacency_matrix : public page_manager { public: static const unsigned int BIT_PER_NODE = 1; static const unsigned int BLOCK_PER_ROW = 4; static const unsigned int NODE_PER_BLOCK = sizeof(page_manager::block_type) * 8 / BIT_PER_NODE; // (byte/block)*(bit/byte)/(bit/node) = (node/block) static const unsigned int COLUMN_HEADER_BLOCKS = BLOCK_PER_ROW; static const unsigned int MAX_COLUMN_NODES = NODE_PER_BLOCK * BLOCK_PER_ROW; static const unsigned int ROW_HEADER_BLOCKS = (page_manager::BLOCK_COUNT - COLUMN_HEADER_BLOCKS) / (NODE_PER_BLOCK * COLUMN_HEADER_BLOCKS + 1); static const unsigned int MAX_ROW_NODES = NODE_PER_BLOCK * ROW_HEADER_BLOCKS; static const unsigned int ROW_PADDING = (page_manager::BLOCK_COUNT - MAX_ROW_NODES); adjacency_matrix( unsigned int rows, unsigned int cols ); size_t free_pages_count() const; size_t row_padding() const; size_t column_padding() const; void resize( unsigned int rows, unsigned int cols ); friend std::ostream & operator<<( std::ostream & out, const adjacency_matrix & rhs ); virtual ~adjacency_matrix(); protected: unsigned int m_rows, m_cols; unsigned int m_row_pages, m_col_pages; }; #endif // ADJACENCY_MATRIX_H_
{ "content_hash": "ae3f3a9671a70289bc8498949627d163", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 152, "avg_line_length": 39.69565217391305, "alnum_prop": 0.5651697699890471, "repo_name": "putnampp/clotho", "id": "b0b90651bb7cf384fcaeaa13c84524de5c4bb090", "size": "2739", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/cuda/qtl/complex_adjacency_matrix.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2235" }, { "name": "C++", "bytes": "1925404" }, { "name": "CMake", "bytes": "30518" }, { "name": "Cuda", "bytes": "65398" }, { "name": "Makefile", "bytes": "331" }, { "name": "Python", "bytes": "8217" } ], "symlink_target": "" }
from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class ListLocations(Choreography): def __init__(self, temboo_session): """ Create a new instance of the ListLocations Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(ListLocations, self).__init__(temboo_session, '/Library/CorpWatch/Lists/ListLocations') def new_input_set(self): return ListLocationsInputSet() def _make_result_set(self, result, path): return ListLocationsResultSet(result, path) def _make_execution(self, session, exec_id, path): return ListLocationsChoreographyExecution(session, exec_id, path) class ListLocationsInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the ListLocations Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_APIKey(self, value): """ Set the value of the APIKey input for this Choreo. ((optional, string) The APIKey from CorpWatch if you have one.) """ super(ListLocationsInputSet, self)._set_input('APIKey', value) def set_Address(self, value): """ Set the value of the Address input for this Choreo. ((optional, string) Enter an address fragment to search for. This can be either a street address, city, or state/subregion.) """ super(ListLocationsInputSet, self)._set_input('Address', value) def set_CountryCode(self, value): """ Set the value of the CountryCode input for this Choreo. ((optional, string) Enter an ISO-3166 formatted country code. ) """ super(ListLocationsInputSet, self)._set_input('CountryCode', value) def set_Index(self, value): """ Set the value of the Index input for this Choreo. ((optional, integer) Set the index number of the first result to be returned. The index of the first result is 0.) """ super(ListLocationsInputSet, self)._set_input('Index', value) def set_Limit(self, value): """ Set the value of the Limit input for this Choreo. ((optional, integer) The number of results to be returned. Defaults to 100. Maximum is 5000.) """ super(ListLocationsInputSet, self)._set_input('Limit', value) def set_MaxYear(self, value): """ Set the value of the MaxYear input for this Choreo. ((optional, integer) Indicate desired year of the most recent appearance in SEC filing data (e.g. indicating 2007 will search for companies that ceased filing in 2007).) """ super(ListLocationsInputSet, self)._set_input('MaxYear', value) def set_MinYear(self, value): """ Set the value of the MinYear input for this Choreo. ((optional, integer) Indicate desired year of the earliest appearance in SEC filing data (e.g. indicating 2004 will search for companies that started filing in 2004).) """ super(ListLocationsInputSet, self)._set_input('MinYear', value) def set_PostalCode(self, value): """ Set the value of the PostalCode input for this Choreo. ((optional, integer) Enter a postal code to be searched.) """ super(ListLocationsInputSet, self)._set_input('PostalCode', value) def set_ResponseType(self, value): """ Set the value of the ResponseType input for this Choreo. ((optional, string) Specify json or xml for the type of response to be returned. Defaults to xml.) """ super(ListLocationsInputSet, self)._set_input('ResponseType', value) def set_Type(self, value): """ Set the value of the Type input for this Choreo. ((optional, string) Indicates the origin of the location information found. Acceptable values: relation_loc, business, mailing, state_of_incorp. See documentation for more info.) """ super(ListLocationsInputSet, self)._set_input('Type', value) def set_Year(self, value): """ Set the value of the Year input for this Choreo. ((optional, integer) If a year is specified, only records for that year will be returned and the data in the company objects returned will be set appropriately for the request year. Defaults to most recent.) """ super(ListLocationsInputSet, self)._set_input('Year', value) class ListLocationsResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the ListLocations Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from CorpWatch.) """ return self._output.get('Response', None) class ListLocationsChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return ListLocationsResultSet(response, path)
{ "content_hash": "66c032b3b1aba7cd410fed3ad2d7aca1", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 264, "avg_line_length": 49.34905660377358, "alnum_prop": 0.6855285796214873, "repo_name": "lupyuen/RaspberryPiImage", "id": "5e7887f57566f2b81f7c0b27815002bb402c157f", "size": "6116", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "home/pi/GrovePi/Software/Python/others/temboo/Library/CorpWatch/Lists/ListLocations.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Arduino", "bytes": "82308" }, { "name": "C", "bytes": "3197439" }, { "name": "C#", "bytes": "33056" }, { "name": "C++", "bytes": "1020255" }, { "name": "CSS", "bytes": "208338" }, { "name": "CoffeeScript", "bytes": "87200" }, { "name": "Eagle", "bytes": "1632170" }, { "name": "Go", "bytes": "3646" }, { "name": "Groff", "bytes": "286691" }, { "name": "HTML", "bytes": "41527" }, { "name": "JavaScript", "bytes": "403603" }, { "name": "Makefile", "bytes": "33808" }, { "name": "Objective-C", "bytes": "69457" }, { "name": "Perl", "bytes": "96047" }, { "name": "Processing", "bytes": "1304" }, { "name": "Python", "bytes": "13358098" }, { "name": "Shell", "bytes": "68795" }, { "name": "TeX", "bytes": "4317" } ], "symlink_target": "" }
/* global wpseoReplaceVarsL10n, require */ var forEach = require( "lodash/forEach" ); var filter = require( "lodash/filter" ); var isUndefined = require( "lodash/isUndefined" ); var ReplaceVar = require( "./values/replaceVar" ); ( function() { "use strict"; var modifiableFields = [ "content", "title", "snippet_title", "snippet_meta", "primary_category", "data_page_title", "data_meta_desc", ]; var placeholders = {}; var taxonomyElements = {}; /** * Variable replacement plugin for WordPress. * * @returns {void} */ var YoastReplaceVarPlugin = function( app ) { this._app = app; this._app.registerPlugin( "replaceVariablePlugin", { status: "ready" } ); this.registerReplacements(); this.registerModifications(); this.registerEvents(); }; /** * GENERIC */ /** * Registers all the placeholders and their replacements. * * @returns {void} */ YoastReplaceVarPlugin.prototype.registerReplacements = function() { this.addReplacement( new ReplaceVar( "%%currentdate%%", "currentdate" ) ); this.addReplacement( new ReplaceVar( "%%currentday%%", "currentday" ) ); this.addReplacement( new ReplaceVar( "%%currentmonth%%", "currentmonth" ) ); this.addReplacement( new ReplaceVar( "%%currenttime%%", "currenttime" ) ); this.addReplacement( new ReplaceVar( "%%currentyear%%", "currentyear" ) ); this.addReplacement( new ReplaceVar( "%%date%%", "date" ) ); this.addReplacement( new ReplaceVar( "%%id%%", "id" ) ); this.addReplacement( new ReplaceVar( "%%page%%", "page" ) ); this.addReplacement( new ReplaceVar( "%%searchphrase%%", "searchphrase" ) ); this.addReplacement( new ReplaceVar( "%%sitedesc%%", "sitedesc" ) ); this.addReplacement( new ReplaceVar( "%%sitename%%", "sitename" ) ); this.addReplacement( new ReplaceVar( "%%category%%", "category" ) ); this.addReplacement( new ReplaceVar( "%%focuskw%%", "keyword", { source: "app", aliases: [ "%%keyword%%" ], } ) ); this.addReplacement( new ReplaceVar( "%%term_description%%", "text", { source: "app", scope: [ "term", "category", "tag" ], aliases: [ "%%tag_description%%", "%%category_description%%" ], } ) ); this.addReplacement( new ReplaceVar( "%%term_title%%", "term_title", { scope: [ "post", "term" ], } ) ); this.addReplacement( new ReplaceVar( "%%title%%", "title", { source: "app", scope: [ "post", "term", "page" ], } ) ); this.addReplacement( new ReplaceVar( "%%parent_title%%", "title", { source: "app", scope: [ "page", "category" ], } ) ); this.addReplacement( new ReplaceVar( "%%excerpt%%", "excerpt", { source: "app", scope: [ "post" ], aliases: [ "%%excerpt_only%%" ], } ) ); this.addReplacement( new ReplaceVar( "%%primary_category%%", "primaryCategory", { source: "app", scope: [ "post" ], } ) ); this.addReplacement( new ReplaceVar( "%%sep%%(\\s*%%sep%%)*", "sep" ) ); }; /** * Register all the necessary events to live replace, placeholders. * * @returns {void} */ YoastReplaceVarPlugin.prototype.registerEvents = function() { var currentScope = wpseoReplaceVarsL10n.scope; if ( currentScope === "post" ) { // Set events for each taxonomy box. jQuery( ".categorydiv" ).each( this.bindTaxonomyEvents.bind( this ) ); } if ( currentScope === "post" || currentScope === "page" ) { // Add support for custom fields as well. jQuery( "#postcustomstuff > #list-table" ).each( this.bindFieldEvents.bind( this ) ); } }; /** * Add a replacement object to be used when replacing placeholders. * * @param {ReplaceVar} replacement The replacement to add to the placeholders. * * @returns {void} */ YoastReplaceVarPlugin.prototype.addReplacement = function( replacement ) { placeholders[ replacement.placeholder ] = replacement; }; /** * Removes a replacement if it exists. * * @param {ReplaceVar} replacement The replacement to remove. * * @returns {void} */ YoastReplaceVarPlugin.prototype.removeReplacement = function( replacement ) { delete placeholders[ replacement.getPlaceholder() ]; }; /** * Registers the modifications for the plugin on initial load. * * @returns {void} */ YoastReplaceVarPlugin.prototype.registerModifications = function() { var callback = this.replaceVariables.bind( this ); forEach( modifiableFields, function( field ) { this._app.registerModification( field, callback, "replaceVariablePlugin", 10 ); }.bind( this ) ); }; /** * Runs the different replacements on the data-string. * * @param {string} data The data that needs its placeholders replaced. * @returns {string} The data with all its placeholders replaced by actual values. */ YoastReplaceVarPlugin.prototype.replaceVariables = function( data ) { if ( ! isUndefined( data ) ) { data = this.termtitleReplace( data ); // This order currently needs to be maintained until we can figure out a nicer way to replace this. data = this.parentReplace( data ); data = this.replaceCustomTaxonomy( data ); data = this.replacePlaceholders( data ); } return data; }; /** * Retrieves the object containing the replacements for the placeholders. Defaults to wpseoReplaceVarsL10n. * * @param {Object} placeholderOptions Placeholder options object containing a replacement and source. * @returns {Object} The replacement object to use. */ YoastReplaceVarPlugin.prototype.getReplacementSource = function( placeholderOptions ) { if ( placeholderOptions.source === "app" ) { return this._app.rawData; } if ( placeholderOptions.source === "direct" ) { return "direct"; } return wpseoReplaceVarsL10n.replace_vars; }; /** * Gets the proper replacement variable. * * @param {ReplaceVar} replaceVar The replacevar object to use for its source, scope and replacement property. * @returns {string} The replacement for the placeholder. */ YoastReplaceVarPlugin.prototype.getReplacement = function( replaceVar ) { var replacementSource = this.getReplacementSource( replaceVar.options ); if ( replaceVar.inScope( wpseoReplaceVarsL10n.scope ) === false ) { return ""; } if ( replacementSource === "direct" ) { return replaceVar.replacement; } return replacementSource[ replaceVar.replacement ] || ""; }; /** * Replaces placeholder variables with their replacement value. * * @param {string} text The text to have its placeholders replaced. * @returns {string} The text in which the placeholders have been replaced. */ YoastReplaceVarPlugin.prototype.replacePlaceholders = function( text ) { forEach( placeholders, function( replaceVar ) { text = text.replace( new RegExp( replaceVar.getPlaceholder( true ), "g" ), this.getReplacement( replaceVar ) ); }.bind( this ) ); return text; }; /** * Declares reloaded with YoastSEO. * * @returns {void} */ YoastReplaceVarPlugin.prototype.declareReloaded = function() { this._app.pluginReloaded( "replaceVariablePlugin" ); }; /** * TAXONOMIES */ /** * Gets the taxonomy name from categories. * The logic of this function is inspired by: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/ * * @param {Object} checkbox The checkbox to parse to retrieve the label. * @returns {string} The category name. */ YoastReplaceVarPlugin.prototype.getCategoryName = function( checkbox ) { // Take the parent of checkbox with type label and clone it. var clonedLabel = checkbox.parent( "label" ).clone(); // Finds child elements and removes them so we only get the label's text left. clonedLabel.children().remove(); // Returns the trimmed text value, return clonedLabel.text().trim(); }; /** * Gets the checkbox-based taxonomies that are available on the current page and based on their checked state. * * @param {Object} checkboxes The checkboxes to check. * @param {string} taxonomyName The taxonomy name to use as a reference. * * @returns {void} */ YoastReplaceVarPlugin.prototype.parseTaxonomies = function( checkboxes, taxonomyName ) { if ( isUndefined( taxonomyElements[ taxonomyName ] ) ) { taxonomyElements[ taxonomyName ] = {}; } forEach( checkboxes, function( checkbox ) { checkbox = jQuery( checkbox ); var taxonomyID = checkbox.val(); taxonomyElements[ taxonomyName ][ taxonomyID ] = { label: this.getCategoryName( checkbox ), checked: checkbox.prop( "checked" ), }; }.bind( this ) ); }; /** * Get the taxonomies that are available on the current page. * * @param {Object} targetMetaBox The HTML element to use as a source for the taxonomies. * @returns {void} */ YoastReplaceVarPlugin.prototype.getAvailableTaxonomies = function( targetMetaBox ) { var checkboxes = jQuery( targetMetaBox ).find( "input[type=checkbox]" ); var taxonomyName = jQuery( targetMetaBox ).attr( "id" ).replace( "taxonomy-", "" ); if ( checkboxes.length > 0 ) { this.parseTaxonomies( checkboxes, taxonomyName ); } this.declareReloaded(); }; /** * Binding events for each taxonomy metabox element. * * @param {int} index The index of the element. * @param {Object} taxonomyElement The element to bind the events to. * * @returns {void} */ YoastReplaceVarPlugin.prototype.bindTaxonomyEvents = function( index, taxonomyElement ) { taxonomyElement = jQuery( taxonomyElement ); // Set the events. taxonomyElement.on( "wpListAddEnd", ".categorychecklist", this.getAvailableTaxonomies.bind( this, taxonomyElement ) ); taxonomyElement.on( "change", "input[type=checkbox]", this.getAvailableTaxonomies.bind( this, taxonomyElement ) ); // Get the available taxonomies upon loading the plugin. this.getAvailableTaxonomies( taxonomyElement ); }; /** * Replace the custom taxonomies. * * @param {string} text The text to have its custom taxonomy placeholders replaced. * @return {string} The text in which the custom taxonomy placeholders have been replaced. */ YoastReplaceVarPlugin.prototype.replaceCustomTaxonomy = function( text ) { forEach( taxonomyElements, function( taxonomy, taxonomyName ) { var generatedPlaceholder = "%%ct_" + taxonomyName + "%%"; if ( taxonomyName === "category" ) { generatedPlaceholder = "%%" + taxonomyName + "%%"; } text = text.replace( generatedPlaceholder, this.getTaxonomyReplaceVar( taxonomyName ) ); }.bind( this ) ); return text; }; /** * Returns the string to replace the category taxonomy placeholders. * * @param {string} taxonomyName The name of the taxonomy needed for the lookup. * @returns {string} The categories as a comma separated list. */ YoastReplaceVarPlugin.prototype.getTaxonomyReplaceVar = function( taxonomyName ) { var filtered = []; var toReplaceTaxonomy = taxonomyElements[ taxonomyName ]; // If no replacement is available, return an empty string. if ( isUndefined( toReplaceTaxonomy ) === true ) { return ""; } forEach( toReplaceTaxonomy, function( item ) { if ( item.checked === false ) { return; } filtered.push( item.label ); } ); return jQuery.unique( filtered ).join( ", " ); }; /** * CUSTOM FIELDS */ /** * Get the custom fields that are available on the current page and adds them to the placeholders. * * @param {Object} customFields The custom fields to parse and add. * * @returns {void} */ YoastReplaceVarPlugin.prototype.parseFields = function( customFields ) { jQuery( customFields ).each( function( i, customField ) { var customFieldName = jQuery( "#" + customField.id + "-key" ).val(); var customValue = jQuery( "#" + customField.id + "-value" ).val(); // Register these as new replacevars. The replacement text will be a literal string. this.addReplacement( new ReplaceVar( "%%cf_" + this.sanitizeCustomFieldNames( customFieldName ) + "%%", customValue, { source: "direct" } ) ); }.bind( this ) ); }; /** * Removes the custom fields from the placeholders. * * @param {Object} customFields The fields to parse and remove. * * @returns {void} */ YoastReplaceVarPlugin.prototype.removeFields = function( customFields ) { jQuery( customFields ).each( function( i, customField ) { var customFieldName = jQuery( "#" + customField.id + "-key" ).val(); // Register these as new replacevars this.removeReplacement( "%%cf_" + this.sanitizeCustomFieldNames( customFieldName ) + "%%" ); }.bind( this ) ); }; /** * Sanitizes the custom field's name by replacing spaces with underscores for easier matching. * * @param {string} customFieldName The field name to sanitize. * @returns {string} The sanitized field name. */ YoastReplaceVarPlugin.prototype.sanitizeCustomFieldNames = function( customFieldName ) { return customFieldName.replace( " ", "_" ); }; /** * Get the custom fields that are available on the current page. * * @param {object} targetMetaBox The HTML element to use as a source for the taxonomies. * @returns {void} */ YoastReplaceVarPlugin.prototype.getAvailableFields = function( targetMetaBox ) { // Remove all the custom fields prior. This ensures that deleted fields don't show up anymore. this.removeCustomFields(); var textFields = jQuery( targetMetaBox ).find( "#the-list > tr:visible" ); if ( textFields.length > 0 ) { this.parseFields( textFields ); } this.declareReloaded(); }; /** * Binding events for each custom field element. * * @param {int} index The index of the element. * @param {Object} customFieldElement The element to bind the events to. * * @returns {void} */ YoastReplaceVarPlugin.prototype.bindFieldEvents = function( index, customFieldElement ) { customFieldElement = jQuery( customFieldElement ); var customFieldElementList = customFieldElement.find( "#the-list" ); customFieldElementList.on( "wpListDelEnd.wpseoCustomFields", this.getAvailableFields.bind( this, customFieldElement ) ); customFieldElementList.on( "wpListAddEnd.wpseoCustomFields", this.getAvailableFields.bind( this, customFieldElement ) ); customFieldElementList.on( "input.wpseoCustomFields", ".textarea", this.getAvailableFields.bind( this, customFieldElement ) ); customFieldElementList.on( "click.wpseoCustomFields", ".button + .updatemeta", this.getAvailableFields.bind( this, customFieldElement ) ); // Get the available fields upon loading the plugin. this.getAvailableFields( customFieldElement ); }; /** * Looks for custom fields in the list of placeholders and deletes them. * * @returns {void} */ YoastReplaceVarPlugin.prototype.removeCustomFields = function() { var customFields = filter( placeholders, function( item, key ) { return key.indexOf( "%%cf_" ) > -1; } ); forEach( customFields, function( item ) { this.removeReplacement( item ); }.bind( this ) ); }; /** * SPECIALIZED REPLACES */ /** * Replaces %%term_title%% with the title of the term. * * @param {string} data The data that needs its placeholders replaced. * @returns {string} The data with all its placeholders replaced by actual values. */ YoastReplaceVarPlugin.prototype.termtitleReplace = function( data ) { var term_title = this._app.rawData.name; data = data.replace( /%%term_title%%/g, term_title ); return data; }; /** * Replaces %%parent_title%% with the selected value from selectbox (if available on pages only). * * @param {string} data The data that needs its placeholders replaced. * @returns {string} The data with all its placeholders replaced by actual values. */ YoastReplaceVarPlugin.prototype.parentReplace = function( data ) { var parent = jQuery( "#parent_id, #parent" ).eq( 0 ); if ( this.hasParentTitle( parent ) ) { data = data.replace( /%%parent_title%%/, this.getParentTitleReplacement( parent ) ); } return data; }; /** * Checks whether or not there's a parent title available. * * @returns {boolean} Whether or not there is a parent title present. */ YoastReplaceVarPlugin.prototype.hasParentTitle = function( parent ) { return ( ! isUndefined( parent ) && ! isUndefined( parent.prop( "options" ) ) ); }; /** * Gets the replacement for the parent title. * * @param {Object} parent The parent object to use to look for the selected option. * @returns {string} The string to replace the placeholder with. */ YoastReplaceVarPlugin.prototype.getParentTitleReplacement = function( parent ) { var parentText = parent.find( "option:selected" ).text(); if ( parentText === wpseoReplaceVarsL10n.no_parent_text ) { return ""; } return parentText; }; window.YoastReplaceVarPlugin = YoastReplaceVarPlugin; }() );
{ "content_hash": "ced0c23b53d10f718467747d21182d93", "timestamp": "", "source": "github", "line_count": 527, "max_line_length": 140, "avg_line_length": 31.76280834914611, "alnum_prop": 0.6825975267339746, "repo_name": "TropicalRobot/finding-beyond", "id": "32362379eb79617a572f4c8db504867088ec8089", "size": "16739", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "public/app/plugins/wordpress-seo-premium/js/src/wp-seo-replacevar-plugin.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "373662" }, { "name": "JavaScript", "bytes": "645951" }, { "name": "PHP", "bytes": "2540687" }, { "name": "Ruby", "bytes": "2383" }, { "name": "Shell", "bytes": "602" } ], "symlink_target": "" }
import {TestComponentBuilder} from '@angular/compiler/testing'; import {Component} from '@angular/core'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {disableDeprecatedForms, provideForms} from '@angular/forms/index'; import {t} from '../../frameworks/test/index'; import {TEST_CORE_PROVIDERS} from '../../frameworks/core/testing/index'; import {SignupComponent} from './signup.component'; export function main() { t.describe('@Component: signupComponent', () => { // Disable old forms let providerArr: any[]; t.be(() => { providerArr = [disableDeprecatedForms(), provideForms()]; }); t.it('should work', t.inject([TestComponentBuilder], (tcb: TestComponentBuilder) => { tcb.createAsync(TestComponent) .then((rootTC:any) => { let aboutDOMEl = rootTC.debugElement.children[0].nativeElement; t.e(getDOM().querySelectorAll(aboutDOMEl, 'h2')[0].textContent).toEqual('Features'); }); })); }); } @Component({ viewProviders: [ TEST_CORE_PROVIDERS() ], selector: 'test-cmp', directives: [SignupComponent], template: '<sd-signup></sd-signup>' }) class TestComponent {}
{ "content_hash": "53948f13cff1bec616f1fd5ac0d14a59", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 96, "avg_line_length": 32.432432432432435, "alnum_prop": 0.6591666666666667, "repo_name": "BlackMr/angular2seed2new", "id": "d5d9a65ea372d3a2996029679925d36b492b2e3e", "size": "1200", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/client/app/components/signup/signup.component.spec.ts", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "4321" }, { "name": "HTML", "bytes": "20325" }, { "name": "JavaScript", "bytes": "8854" }, { "name": "TypeScript", "bytes": "98611" } ], "symlink_target": "" }
class CreateVotes < ActiveRecord::Migration def change create_table :votes do |t| t.string :votable_type t.integer :votable_id t.references :user t.integer :value t.timestamps null: false end end end
{ "content_hash": "c4c7dbace0907296915b13791ed086c9", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 43, "avg_line_length": 20.25, "alnum_prop": 0.6460905349794238, "repo_name": "anthonycastelli01/hacker-news-clone", "id": "90fa678688b899429264e08d91a9b6f35faabe89", "size": "243", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20150922100420_create_votes.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "674" }, { "name": "HTML", "bytes": "1671" }, { "name": "JavaScript", "bytes": "1387" }, { "name": "Ruby", "bytes": "14596" } ], "symlink_target": "" }
<div class="status"> <div class="status_content"> <a href="<?php echo $base_url; ?>/user/<?php echo $this->escape($status['user_name']); ?>"> <?php echo $this->escape($status['user_name']); ?> </a> <?php echo $this->escape($status['body']); ?> </div> <div> <a href="<?php echo $base_url; ?>/user/<?php echo $this->escape($status['user_name']); ?>/status/<?php echo $this->escape($status['id']); ?>"> <?php echo $this->escape($status['created_at']); ?> </a> </div> </div>
{ "content_hash": "a871c64aee40cdb68b611ca1d51fcd59", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 99, "avg_line_length": 39.92857142857143, "alnum_prop": 0.49731663685152055, "repo_name": "kenjis/perfect-php-mini-blog", "id": "dc514e74935d31d26b2d545d01897873907cc0dd", "size": "559", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "views/status/status.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "47236" } ], "symlink_target": "" }
if (exist('translation', 'var') == 0) translation = true; end if (exist('motherEnvelope', 'var') == 0) motherEnvelope = pi; end if (exist('numRuns','var') == 0) numRuns = 100; end if (exist('ratio','var') == 0) ratio = true; end if (exist('dataBaseDir', 'var') == 0) dataBaseDir = '../data/rotVsBandPostFix/notSpringed/'; end if (exist('figsBaseDir', 'var') == 0) figsBaseDir = '../../figures/rotVsBandPostFix/notSpringed/'; end if (motherEnvelope == pi) envDir = 'mEnvP/'; elseif (motherEnvelope == 2*pi) envDir = 'mEnv2P/'; end if (translation) transDir = 'translation/'; else transDir = 'noTranslation/'; end dataDir = [dataBaseDir transDir envDir]; dataFiles = getAllFiles(dataDir); fixedWidths = [pi/2 pi/2.5 pi/3 pi/3.5 pi/4 pi/5 pi/6 pi/7 pi/8 pi/10 ... pi/12 pi/15 pi/18]; fixedWidthFiles = {'Po2', 'Po2p5', 'Po3', 'Po3p5', 'Po4', 'Po5', ... 'Po6', 'Po7', 'Po8', 'Po10', 'Po12', 'Po15', 'Po18'}; for j = 1:length(fixedWidths) %%%TODO: This is done stupidly. fixedWidth = fixedWidths(j); fixedWidthFile = ['ew' char(fixedWidthFiles(j))]; plotXval = []; plotXratio = []; plotYpsi = []; plotYx = []; plotYy = []; errorY = []; errorX = []; errorPsi = []; for i = 1:length(dataFiles) dataFile = char(dataFiles(i)); fileParts = strsplit(dataFile,'/'); dataFileFull = char(fileParts(7)); fileNameParts = strsplit(dataFileFull,'.csv'); %resetting dataFile dataFile = char(fileNameParts(1)); fileNameStripped = strsplit(dataFile,'bw'); fileNameStripped = strsplit(char(fileNameStripped(2)),'ew'); bandWidth = char(fileNameStripped(1)); envWidth = char(fileNameStripped(2)); if (strcmp(envWidth, 'P')) envWidth = pi; else envWidthParts = strsplit(envWidth,'o'); envNum = char(envWidthParts(1)); if (strcmp(envNum, 'P')) envNum = pi; else envNum = 2*pi; end envDen = str2double(char(envWidthParts(2))); envWidth = envNum/envDen; end if (strcmp(bandWidth, '0') || strcmp(bandWidth, 'P')) if (strcmp(bandWidth, '0')) bandWidth = 0; else bandWidth = pi; end else bandWidthParts = strsplit(bandWidth,'o'); bandNum = char(bandWidthParts(1)); if (strcmp(bandNum, 'P')) bandNum = pi; else bandNum = 2*pi; end bandDen = str2double(char(bandWidthParts(2))); bandWidth = bandNum/bandDen; end if (envWidth == fixedWidth) if (bandWidth == pi/2) continue; end display(['grabbing Data for file ' dataFileFull]); run parameters csvrange = [rowStart colStart rowStart+numRuns-1 colStart+2]; DATA = csvread(dataFileFull,rowStart,colStart,csvrange); x = DATA(:,1); y = DATA(:,2); psi = abs((DATA(:,3)-pi/2)*180/pi); plotXval = [plotXval bandWidth]; plotXratio = [plotXratio bandWidth/envWidth]; plotYpsi = [plotYpsi mean(psi)]; plotYx = [plotYx mean(x)]; plotYy = [plotYy mean(y)]; errorPsi = [errorPsi std(psi)]; errorX = [errorX std(x)]; errorY = [errorY std(y)]; end end [sortedXval,indices] = sort(plotXval*180/pi); sortedXratio = plotXratio(indices); sortedYpsi = plotYpsi(indices); sortedYx = plotYx(indices); sortedYy = plotYy(indices); sortedErrorPsi = errorPsi(indices); sortedErrorX = errorX(indices); sortedErrorY = errorY(indices); fig = figure('visible', 'off'); if (translation) if (ratio) fullRange = [sortedXratio(1) sortedXratio(length(sortedXratio))]; subplot(3,1,1); hold on; errorbar(sortedXratio,sortedYpsi,sortedErrorPsi); ideal = plot(fullRange, [90 90], 'g--'); initial = plot(fullRange, [180/8 180/8], 'k--'); xlabel('(Band Width)/(Daughter Envelope Width)'); ylabel('Abs(Rotation)'); legend([ideal, initial],{'Full Half-turn (ideal)','Initial orientation'}); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subplot(3,1,2); hold on; errorbar(sortedXratio,sortedYx,sortedErrorX); ideal = plot(fullRange, [-R1_max/5 -R1_max/5], 'g--'); initial = plot(fullRange, [R1_max/5 R1_max/5], 'b--'); leftEdge = plot(fullRange, [-R1_max, -R1_max], 'r--'); rightEdge = plot(fullRange, [R1_max, R1_max], 'r--'); xlabel('(Band Width)/(Daughter Envelope Width)'); ylabel('Final x positions (mum)'); legend([ideal, initial, leftEdge, rightEdge], ... {'Ideal Ending Position (60-40 line)', ... 'Starting Position (opposite 60-40 line)', ... 'Leftmost Cell Boundary',... 'Rightmost Cell Boundary'}); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subplot(3,1,3); hold on; errorbar(sortedXratio,sortedYy,sortedErrorY); initial = plot(fullRange, [0 0], 'g--'); bottomEdge = plot(fullRange, [-R2_max, -R2_max], 'r--'); topEdge = plot(fullRange, [R2_max, R2_max], 'r--'); xlabel('(Band Width)/(Daughter Envelope Width)'); ylabel('Final x positions (mum)'); legend([initial, bottomEdge, topEdge], ... {'Initial Position', ... 'Lower Cell Boundary',... 'Upper Cell Boundary'}); else subplot(3,1,1); hold on; errorbar(sortedXval,sortedYpsi,sortedErrorPsi); xlabel('Band Width'); ylabel('Abs(Rotation)'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subplot(3,1,2); hold on; errorbar(sortedXval,sortedYx,sortedErrorX); xlabel('Band Width (degrees)'); ylabel('Final x positions (mum)'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subplot(3,1,3); hold on; errorbar(sortedXval,sortedYy,sortedErrorY); xlabel('Band Width (degrees)'); ylabel('Final x positions (mum)'); end else if (ratio) hold on; errorbar(sortedXratio,sortedYpsi,sortedErrorPsi); xlabel('(Band Width)/(Daughter Envelope Width)'); ylabel('Abs(Rotation)'); else hold on; errorbar(sortedXval,sortedYpsi,sortedErrorPsi); xlabel('Band Width'); ylabel('Abs(Rotation)'); end end figureFile = [figsBaseDir transDir envDir fixedWidthFile]; print(fig,'-dpdf', figureFile); %savefig(figureFile); saveas(fig,[figureFile '.fig']); end
{ "content_hash": "fdebf693fa1b6a438e4bd391abda220c", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 86, "avg_line_length": 37.215384615384615, "alnum_prop": 0.5070965963896927, "repo_name": "mmcdermott/nuclearKineticsModelling", "id": "7093e1eab0156e294ea24878105aa49bff5375c0", "size": "7257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plottingCode/plotter.m", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "383103" }, { "name": "JavaScript", "bytes": "293" }, { "name": "Makefile", "bytes": "477" }, { "name": "Matlab", "bytes": "157470" }, { "name": "Shell", "bytes": "5940" } ], "symlink_target": "" }
use strict; use warnings; use Getopt::Long qw(:config posix_default bundling no_ignorecase); use Dpkg (); use Dpkg::Gettext; use Dpkg::ErrorHandling; use Dpkg::Arch qw(get_host_arch); use Dpkg::BuildProfiles qw(get_build_profiles set_build_profiles); use Dpkg::Deps; use Dpkg::Control::Info; textdomain('dpkg-dev'); sub version() { printf(_g("Debian %s version %s.\n"), $Dpkg::PROGNAME, $Dpkg::PROGVERSION); exit(0); } sub usage { printf _g( 'Usage: %s [<option>...] [<control-file>]') . "\n\n" . _g( 'Options: -A ignore Build-Depends-Arch and Build-Conflicts-Arch. -B ignore Build-Depends-Indep and Build-Conflicts-Indep. -d build-deps use given string as build dependencies instead of retrieving them from control file -c build-conf use given string for build conflicts instead of retrieving them from control file -a arch assume given host architecture -P profiles assume given build profiles (comma-separated list) --admindir=<directory> change the administrative directory. -?, --help show this help message. --version show the version.') . "\n\n" . _g( '<control-file> is the control file to process (default: debian/control).') . "\n", $Dpkg::PROGNAME; } my $ignore_bd_arch = 0; my $ignore_bd_indep = 0; my ($bd_value, $bc_value); my $bp_value; my $host_arch = get_host_arch(); my $admindir = $Dpkg::ADMINDIR; my @options_spec = ( 'help|?' => sub { usage(); exit(0); }, 'version' => \&version, 'A' => \$ignore_bd_arch, 'B' => \$ignore_bd_indep, 'd=s' => \$bd_value, 'c=s' => \$bc_value, 'a=s' => \$host_arch, 'P=s' => \$bp_value, 'admindir=s' => \$admindir, ); { local $SIG{__WARN__} = sub { usageerr($_[0]) }; GetOptions(@options_spec); } # Update currently active build profiles. set_build_profiles(split(/,/, $bp_value)) if ($bp_value); my @build_profiles = get_build_profiles(); my $controlfile = shift || 'debian/control'; my $control = Dpkg::Control::Info->new($controlfile); my $fields = $control->get_source(); my $facts = parse_status("$admindir/status"); unless (defined($bd_value) or defined($bc_value)) { my @bd_list = ('build-essential:native', $fields->{'Build-Depends'}); push @bd_list, $fields->{'Build-Depends-Arch'} if not $ignore_bd_arch; push @bd_list, $fields->{'Build-Depends-Indep'} if not $ignore_bd_indep; $bd_value = deps_concat(@bd_list); my @bc_list = ($fields->{'Build-Conflicts'}); push @bc_list, $fields->{'Build-Conflicts-Arch'} if not $ignore_bd_arch; push @bc_list, $fields->{'Build-Conflicts-Indep'} if not $ignore_bd_indep; $bc_value = deps_concat(@bc_list); } my (@unmet, @conflicts); if ($bd_value) { push @unmet, build_depends('Build-Depends/Build-Depends-Arch/Build-Depends-Indep', deps_parse($bd_value, reduce_restrictions => 1, build_dep => 1, build_profiles => \@build_profiles, host_arch => $host_arch), $facts); } if ($bc_value) { push @conflicts, build_conflicts('Build-Conflicts/Build-Conflicts-Arch/Build-Conflicts-Indep', deps_parse($bc_value, reduce_restrictions => 1, build_dep => 1, build_profiles => \@build_profiles, union => 1, host_arch => $host_arch), $facts); } if (@unmet) { printf { *STDERR } _g('%s: Unmet build dependencies: '), $Dpkg::PROGNAME; print { *STDERR } join(' ', map { $_->output() } @unmet), "\n"; } if (@conflicts) { printf { *STDERR } _g('%s: Build conflicts: '), $Dpkg::PROGNAME; print { *STDERR } join(' ', map { $_->output() } @conflicts), "\n"; } exit 1 if @unmet || @conflicts; # Silly little status file parser that returns a Dpkg::Deps::KnownFacts sub parse_status { my $status = shift; my $facts = Dpkg::Deps::KnownFacts->new(); local $/ = ''; open(my $status_fh, '<', $status) or syserr(_g('cannot open %s'), $status); while (<$status_fh>) { next unless /^Status: .*ok installed$/m; my ($package) = /^Package: (.*)$/m; my ($version) = /^Version: (.*)$/m; my ($arch) = /^Architecture: (.*)$/m; my ($multiarch) = /^Multi-Arch: (.*)$/m; $facts->add_installed_package($package, $version, $arch, $multiarch); if (/^Provides: (.*)$/m) { my $provides = deps_parse($1, reduce_arch => 1, union => 1); next if not defined $provides; foreach (grep { $_->isa('Dpkg::Deps::Simple') } $provides->get_deps()) { $facts->add_provided_package($_->{package}, $_->{relation}, $_->{version}, $package); } } } close $status_fh; return $facts; } # This function checks the build dependencies passed in as the first # parameter. If they are satisfied, returns false. If they are unsatisfied, # an list of the unsatisfied depends is returned. # # Additional parameters that must be passed: # * A reference to a hash of all "ok installed" the packages on the system, # with the hash key being the package name, and the value being the # installed version. # * A reference to a hash, where the keys are package names, and the # value is a true value iff some package installed on the system provides # that package (all installed packages provide themselves) # # Optionally, the architecture the package is to be built for can be passed # in as the 4th parameter. If not set, dpkg will be queried for the build # architecture. sub build_depends { return check_line(1, @_); } # This function is exactly like unmet_build_depends, except it # checks for build conflicts, and returns a list of the packages # that are installed and are conflicted with. sub build_conflicts { return check_line(0, @_); } # This function does all the work. The first parameter is 1 to check build # deps, and 0 to check build conflicts. sub check_line { my $build_depends=shift; my $fieldname=shift; my $dep_list=shift; my $facts=shift; my @unmet=(); unless(defined($dep_list)) { error(_g('error occurred while parsing %s'), $fieldname); } if ($build_depends) { $dep_list->simplify_deps($facts); if ($dep_list->is_empty()) { return (); } else { return $dep_list->get_deps(); } } else { # Build-Conflicts my @conflicts = (); foreach my $dep ($dep_list->get_deps()) { if ($dep->get_evaluation($facts)) { push @conflicts, $dep; } } return @conflicts; } }
{ "content_hash": "25949360f70884ca223f7ffa5c7f268b", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 95, "avg_line_length": 31.165853658536584, "alnum_prop": 0.626232587259352, "repo_name": "nisc-code/dpkg", "id": "2cc8ba067f2c62f73a8eb586d294543ad33e9b46", "size": "7250", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "dpkg-1.17.5ubuntu5.3/scripts/dpkg-checkbuilddeps.pl", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "1230808" }, { "name": "C++", "bytes": "205828" }, { "name": "Groff", "bytes": "2894069" }, { "name": "Lex", "bytes": "5827" }, { "name": "LiveScript", "bytes": "11841" }, { "name": "M4", "bytes": "124171" }, { "name": "Makefile", "bytes": "399696" }, { "name": "Perl", "bytes": "796320" }, { "name": "Shell", "bytes": "172636" } ], "symlink_target": "" }
using System; using System.Collections; namespace ArgusTV.DataContracts { /// <summary> /// A post/live/delete processing command for recordings. /// </summary> public class ProcessingCommand { /// <summary> /// The unique ID of the processing command. /// </summary> public Guid ProcessingCommandId { get; set; } /// <summary> /// The name of the processing command. /// </summary> public string Name { get; set; } /// <summary> /// The full path to the command. /// </summary> public string CommandPath { get; set; } /// <summary> /// The command arguments. /// </summary> public string Arguments { get; set; } /// <summary> /// Is this command assigned to new television schedules by default? /// </summary> public bool IsDefaultTelevision { get; set; } /// <summary> /// Is this command assigned to new radio schedules by default? /// </summary> public bool IsDefaultRadio { get; set; } /// <summary> /// Defines when the command runs. /// </summary> public ProcessingRunMode RunMode { get; set; } /// <summary> /// If the run mode is PostAtTime this is the hours part of the time to run the command. /// </summary> public int? RunAtHours { get; set; } /// <summary> /// If the run mode is PostAtTime this is the minutes part of the time to run the command. /// </summary> public int? RunAtMinutes { get; set; } } }
{ "content_hash": "f896f24226d493fe80e8bf899b2917d8", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 98, "avg_line_length": 28.80701754385965, "alnum_prop": 0.5523751522533495, "repo_name": "hamstercat/Emby.Plugins", "id": "f89e67324535360f5a60b438bd3b35e65883fc12", "size": "2463", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "MediaBrowser.Plugins.ArgusTV/SourceArgus/DataContracts/ProcessingCommand.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "8544445" }, { "name": "HTML", "bytes": "206570" } ], "symlink_target": "" }
// Copyright (c) 2012 Markus Alexander Kuppe. All rights reserved. package tlc2.tool.distributed.fp; import java.io.Serializable; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import tlc2.tool.distributed.TLCWorker; /** * Contrary to {@link FPSetManager}, this class is a {@link UnicastRemoteObject} * . This results in it being a singleton for a distributed TLC model checker * and thus a single point of failure and bottleneck.<br> * On the up side, it results in {@link TLCWorker}s seeing a consistent * distributed fingerprint set at all times. */ @SuppressWarnings("serial") public class DynamicFPSetManager extends FPSetManager implements Serializable { private int expectedNumOfServers; public DynamicFPSetManager(int expectedNumOfServers) throws RemoteException { super(); // If expectedNumOfServers is no power of two, a subset of FPSet // servers will act as passive backups. Each time a FPSet from // the active set is lost, all workers switch over to the next // available passive one on a list. The list has to be known // prior to when the workers start (it's possible to send out // list updates, but it hasn't been implemented). this.expectedNumOfServers = expectedNumOfServers; // Guard against invalid values if (expectedNumOfServers <= 0) { throw new IllegalArgumentException(); } // Round expectedNumOfServers to power of 2 int log = 0; while (expectedNumOfServers > 0) { expectedNumOfServers = expectedNumOfServers / 2; log++; } // Zero upper bits of mask which won't be used when addressing the // fingerprint servers anyway. See IFPSetManager#getFPSetIndex. this.mask = (1L << log) - 1L; } /* (non-Javadoc) * @see tlc2.tool.distributed.IFPSetManager#register(tlc2.tool.distributed.FPSetRMI) */ public synchronized void register(FPSetRMI aFPSet, String hostname) throws FPSetManagerException { // Only accept additional FPSets as long as we haven't reached the // expected number of FPSets. Adding more FPSets to the set than // expected, would screw up the fail over code in reassign() as workers // potentially see an inconsistent list of FPSets. // This is due to the fact that workers immediately retrieve the // FPSetManager once the expected number of FPSets have registered. if (fpSets.size() < expectedNumOfServers) { fpSets.add(new FPSets(aFPSet, hostname)); } else { throw new FPSetManagerException( "Limit for FPset servers reached (" + expectedNumOfServers + "). Cannot handle additional servers"); } } }
{ "content_hash": "a53c45b94fd4257e10b0020cb38fedcb", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 99, "avg_line_length": 39.01470588235294, "alnum_prop": 0.7233320768940822, "repo_name": "tlaplus/tlaplus", "id": "af1f3d10a398a7b798bc1ebe95f33c39fa5fe2a0", "size": "2653", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tlatools/org.lamport.tlatools/src/tlc2/tool/distributed/fp/DynamicFPSetManager.java", "mode": "33188", "license": "mit", "language": [ { "name": "AspectJ", "bytes": "14696" }, { "name": "Batchfile", "bytes": "17418" }, { "name": "CSS", "bytes": "14084" }, { "name": "Groovy", "bytes": "13445" }, { "name": "HTML", "bytes": "6994298" }, { "name": "Java", "bytes": "14476847" }, { "name": "R", "bytes": "3252" }, { "name": "Shell", "bytes": "8406" }, { "name": "TLA", "bytes": "6734190" }, { "name": "TeX", "bytes": "144613" }, { "name": "jq", "bytes": "610" } ], "symlink_target": "" }
import { SourceLocation } from '../SourceLocation' import { SourceType } from '../SourceType' import { assert } from './assert' import { BufferedStream } from './BufferedStream' /** * Helper class for defining the padding (characters to remove, typically * whitespace) in a string or heregexp. Also tracks "line separators", which are * newline characters in multiline single and double quoted strings that should * be turned into space characters. * * Example usage: * * let paddingTracker = new PaddingTracker(source, stream, SSTRING_END); * * // Examine underlying code to see what padding to add. * paddingTracker.fragments[0].content; * * // Mark padding for each fragment, indexed relative to the fragment content. * paddingTracker.fragments[0].markPadding(3, 5); * paddingTracker.fragments[1].markPadding(1, 4); * paddingTracker.fragments[1].markLineSeparator(5); * * // Compute the replacement source locations for the entire string/heregexp. * paddingTracker.computeSourceLocations(); */ export class PaddingTracker { readonly fragments: Array<TrackedFragment> private _originalLocations: Array<SourceLocation> constructor(source: string, stream: BufferedStream, endType: SourceType) { this.fragments = [] this._originalLocations = [] let interpolationLevel = 0 let location do { location = stream.shift() this._originalLocations.push(location) if ( interpolationLevel === 0 && location.type === SourceType.STRING_CONTENT ) { const start = location.index const end = stream.peek().index const content = source.slice(start, end) const index = this.fragments.length this.fragments.push(new TrackedFragment(content, start, end, index)) } else if (location.type === SourceType.INTERPOLATION_START) { interpolationLevel += 1 } else if (location.type === SourceType.INTERPOLATION_END) { interpolationLevel -= 1 } } while (interpolationLevel > 0 || location.type !== endType) } computeSourceLocations(): Array<SourceLocation> { const resultLocations: Array<SourceLocation> = [] let rangeIndex = 0 for (const location of this._originalLocations) { const currentRange = this.fragments[rangeIndex] if ( location.type === SourceType.STRING_CONTENT && currentRange && location.index === currentRange.start ) { resultLocations.push(...currentRange.computeSourceLocations()) rangeIndex++ } else { resultLocations.push(location) } } assert( rangeIndex === this.fragments.length, 'Expected ranges to correspond to original locations.' ) return resultLocations } } export interface PaddingRange { readonly start: number readonly end: number } type LocationEvent = | 'START_PADDING' | 'END_PADDING' | 'START_LINE_SEPARATOR' | 'END_LINE_SEPARATOR' export class TrackedFragment { readonly content: string readonly start: number readonly end: number readonly index: number readonly _paddingRanges: Array<PaddingRange> readonly _lineSeparators: Array<number> constructor(content: string, start: number, end: number, index: number) { this.content = content this.start = start this.end = end this.index = index this._paddingRanges = [] this._lineSeparators = [] } markPadding(startIndex: number, endIndex: number): void { this._paddingRanges.push({ start: startIndex, end: endIndex }) } markLineSeparator(index: number): void { this._lineSeparators.push(index) } computeSourceLocations(): Array<SourceLocation> { if (this.start === this.end) { return [new SourceLocation(SourceType.STRING_CONTENT, this.start)] } // Break the marked ranges down into events, similar to how you might count // paren nesting. At each index, we can then know if we're inside padding, // a line separator, or neither. const eventsByIndex: Array<Array<LocationEvent>> = [] for (let i = 0; i < this.end - this.start + 1; i++) { eventsByIndex.push([]) } for (const range of this._paddingRanges) { eventsByIndex[range.start].push('START_PADDING') eventsByIndex[range.end].push('END_PADDING') } for (const separatorIndex of this._lineSeparators) { eventsByIndex[separatorIndex].push('START_LINE_SEPARATOR') eventsByIndex[separatorIndex + 1].push('END_LINE_SEPARATOR') } const resultLocations: Array<SourceLocation> = [] let lastSourceType = null let paddingDepth = 0 let lineSeparatorDepth = 0 for (let sourceIndex = this.start; sourceIndex < this.end; sourceIndex++) { for (const event of eventsByIndex[sourceIndex - this.start]) { if (event === 'START_PADDING') { paddingDepth += 1 } else if (event === 'END_PADDING') { paddingDepth -= 1 } else if (event === 'START_LINE_SEPARATOR') { lineSeparatorDepth += 1 } else if (event === 'END_LINE_SEPARATOR') { lineSeparatorDepth -= 1 } } assert( paddingDepth >= 0 && lineSeparatorDepth >= 0 && (paddingDepth <= 0 || lineSeparatorDepth <= 0), `Illegal padding state: paddingDepth: ${paddingDepth}, lineSeparatorDepth: ${lineSeparatorDepth}` ) let sourceType if (paddingDepth > 0) { sourceType = SourceType.STRING_PADDING } else if (lineSeparatorDepth > 0) { sourceType = SourceType.STRING_LINE_SEPARATOR } else { sourceType = SourceType.STRING_CONTENT } if (sourceType !== lastSourceType) { resultLocations.push(new SourceLocation(sourceType, sourceIndex)) lastSourceType = sourceType } } return resultLocations } }
{ "content_hash": "933b4be3d112daa166d0f66c4b84d01a", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 105, "avg_line_length": 33.29714285714286, "alnum_prop": 0.6632915737085979, "repo_name": "decaffeinate/coffee-lex", "id": "be7bd58e55331d004cc5f2d89e233793ee37abbe", "size": "5827", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/utils/PaddingTracker.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1816" }, { "name": "Shell", "bytes": "74" }, { "name": "TypeScript", "bytes": "153017" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.apache.metron</groupId> <artifactId>Metron</artifactId> <version>0.4.3</version> <packaging>pom</packaging> <name>Metron</name> <description>Metron Top Level Project</description> <url>https://metron.apache.org/</url> <organization> <name>The Apache Software Foundation</name> <url>https://www.apache.org</url> </organization> <modules> <module>metron-analytics</module> <module>metron-platform</module> <module>metron-deployment</module> <module>metron-contrib</module> <module>metron-interface</module> <module>site-book</module> <module>metron-stellar</module> </modules> <repositories> <repository> <id>clojars.org</id> <url>http://clojars.org/repo</url> </repository> <repository> <id>jcenter</id> <url>https://jcenter.bintray.com/</url> </repository> <repository> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> <checksumPolicy>warn</checksumPolicy> </releases> <snapshots> <enabled>false</enabled> <updatePolicy>never</updatePolicy> <checksumPolicy>fail</checksumPolicy> </snapshots> <id>HDPReleases</id> <name>HDP Releases</name> <url>http://repo.hortonworks.com/content/repositories/releases/</url> <layout>default</layout> </repository> <repository> <id>multiline-release-repo</id> <url>https://raw.github.com/benelog/multiline/master/maven-repository</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <properties> <twitter>@ApacheMetron</twitter> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- base project versions --> <base_storm_version>1.0.1</base_storm_version> <base_flux_version>1.0.1</base_flux_version> <base_kafka_version>0.10.0</base_kafka_version> <base_hadoop_version>2.7.1</base_hadoop_version> <base_hbase_version>1.1.1</base_hbase_version> <base_flume_version>1.5.2</base_flume_version> <!-- full dependency versions --> <global_accumulo_version>1.8.0</global_accumulo_version> <global_antlr_version>4.5</global_antlr_version> <global_opencsv_version>3.7</global_opencsv_version> <global_curator_version>2.7.1</global_curator_version> <global_classindex_version>3.3</global_classindex_version> <global_storm_version>1.0.3</global_storm_version> <global_storm_kafka_version>1.1.0</global_storm_kafka_version> <global_flux_version>${base_flux_version}</global_flux_version> <global_pcap_version>1.7.1</global_pcap_version> <global_kafka_version>0.10.0.1</global_kafka_version> <global_hadoop_version>${base_hadoop_version}</global_hadoop_version> <global_hbase_version>${base_hbase_version}</global_hbase_version> <global_flume_version>${base_flume_version}</global_flume_version> <global_elasticsearch_version>5.6.2</global_elasticsearch_version> <global_json_simple_version>1.1.1</global_json_simple_version> <global_metrics_version>3.0.2</global_metrics_version> <global_junit_version>4.12</global_junit_version> <global_guava_version>17.0</global_guava_version> <global_hbase_guava_version>12.0</global_hbase_guava_version> <global_json_schema_validator_version>2.2.5</global_json_schema_validator_version> <global_slf4j_version>1.7.7</global_slf4j_version> <global_opencsv_version>3.7</global_opencsv_version> <global_java_version>1.8</global_java_version> <global_solr_version>5.2.1</global_solr_version> <global_mockito_version>1.10.19</global_mockito_version> <global_shade_version>2.4.3</global_shade_version> <global_jackson_version>2.7.4</global_jackson_version> <global_errorprone_core_version>2.0.14</global_errorprone_core_version> <global_jar_version>3.0.2</global_jar_version> <global_surefire_version>2.18</global_surefire_version> <global_maven_version>[3.3.1,)</global_maven_version> <global_kryo_version>3.0.3</global_kryo_version> <global_kryo_serializers_version>0.38</global_kryo_serializers_version> <global_reflections_version>0.9.10</global_reflections_version> <global_checkstyle_version>8.0</global_checkstyle_version> <global_log4j_core_version>2.1</global_log4j_core_version> </properties> <profiles> <profile> <id>HDP-2.5.0.0</id> <properties> <hdp_version>2.5.0.0</hdp_version> <build_number>1245</build_number> <global_storm_kafka_version>1.1.0</global_storm_kafka_version> <global_storm_version>${base_storm_version}.${hdp_version}-${build_number}</global_storm_version> <global_kafka_version>${base_kafka_version}.${hdp_version}-${build_number}</global_kafka_version> </properties> </profile> </profiles> <dependencyManagement> <dependencies> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>${global_mockito_version}</version> </dependency> <dependency> <groupId>org.apache.storm</groupId> <artifactId>storm-kafka</artifactId> <version>${global_storm_version}</version> </dependency> </dependencies> </dependencyManagement> <build> <pluginManagement> <plugins> <plugin> <!-- Separates the unit tests from the integration tests. --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>${global_surefire_version}</version> <configuration> <!-- Skip the default running of this plug-in (or everything is run twice...see below) --> <argLine>-Xmx2048m</argLine> <skip>true</skip> <!-- Show 100% of the lines from the stack trace (doesn't work) --> <trimStackTrace>false</trimStackTrace> </configuration> <executions> <execution> <id>unit-tests</id> <phase>test</phase> <goals> <goal>test</goal> </goals> <configuration> <!-- Never skip running the tests when the test phase is invoked --> <skip>false</skip> <includes> <!-- Include unit tests within integration-test phase. --> <include>**/*Test.java</include> </includes> <excludes> <!-- Exclude integration tests within (unit) test phase. --> <exclude>**/*IntegrationTest.java</exclude> </excludes> </configuration> </execution> <execution> <id>integration-tests</id> <phase>integration-test</phase> <goals> <goal>test</goal> </goals> <configuration> <!-- Never skip running the tests when the integration-test phase is invoked --> <skip>false</skip> <includes> <!-- Include integration tests within integration-test phase. --> <include>**/*IntegrationTest.java</include> </includes> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.6</version> <configuration> <tarLongFileMode>posix</tarLongFileMode> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.17</version> <dependencies> <dependency> <groupId>com.puppycrawl.tools</groupId> <artifactId>checkstyle</artifactId> <version>${global_checkstyle_version}</version> </dependency> </dependencies> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.6</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <compilerId>javac-with-errorprone</compilerId> <forceJavacCompilerUse>true</forceJavacCompilerUse> <source>${global_java_version}</source> <compilerArgument>-Xlint:unchecked</compilerArgument> <target>${global_java_version}</target> <showWarnings>true</showWarnings> </configuration> <dependencies> <dependency> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-compiler-javac-errorprone</artifactId> <version>2.8</version> </dependency> <!-- override plexus-compiler-javac-errorprone's dependency on Error Prone with the latest version --> <dependency> <groupId>com.google.errorprone</groupId> <artifactId>error_prone_core</artifactId> <version>${global_errorprone_core_version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.7</version> <configuration> <check /> <formats> <format>html</format> </formats> <aggregate>true</aggregate> </configuration> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.7.9</version> <executions> <execution> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report</id> <phase>prepare-package</phase> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.rat</groupId> <artifactId>apache-rat-plugin</artifactId> <version>0.12</version> <executions> <execution> <phase>verify</phase> <goals> <goal>check</goal> </goals> </execution> </executions> <configuration> <excludes> <exclude>dependencies_with_url.csv</exclude> <!-- In travis we need to pull down maven 3.3.9, so we should exclude it here as it is not our code. --> <exclude>apache-maven-3.3.9/**</exclude> <exclude>**/VERSION</exclude> <exclude>**/*.json</exclude> <exclude>**/*.json.j2</exclude> <exclude>**/*.tokens</exclude> <exclude>**/*.log</exclude> <exclude>**/*.template</exclude> <exclude>**/*.mapping</exclude> <exclude>**/.*</exclude> <exclude>**/.*/**</exclude> <exclude>**/*.seed</exclude> <exclude>**/*.iml</exclude> <exclude>**/ansible.cfg</exclude> <exclude>**/*.rpm</exclude> <exclude>site/**</exclude> <exclude>**/src/main/resources/patterns/**</exclude> <exclude>**/src/main/sample/patterns/**</exclude> <exclude>**/src/test/resources/**</exclude> <exclude>**/src/main/sample/data/**</exclude> <exclude>**/dependency-reduced-pom.xml</exclude> <exclude>**/target/**</exclude> <!-- Files from Chef/bento --> <exclude>**/packer-build/scripts/**</exclude> <exclude>**/packer-build/bin/**</exclude> <!-- Packer/Bento non-source directory --> <exclude>**/packer_cache/**</exclude> <exclude>**/hbase/data/**</exclude> <exclude>**/kafkazk/data/**</exclude> <exclude>**/wait-for-it.sh</exclude> <exclude>**/*.out</exclude> <!-- Directory containing dependencies downloaded by NPM --> <exclude>node_modules/**</exclude> <!-- Nodejs installed locally by the frontend-maven-plugin --> <exclude>node/**</exclude> <!-- Javascript code coverage report generated by Istanbul --> <exclude>coverage/**</exclude> <!-- ACE editor assets are covered in the metron-config NOTICE file --> <exclude>**/src/assets/ace/**</exclude> <exclude>dist/assets/ace/**</exclude> <!-- Generated svg and bundle.css containing Font Awesome fonts are covered in the metron-interface/metron-config README and NOTICE files --> <exclude>dist/*.svg</exclude> <exclude>dist/styles.a0b6b99c10d9a13dc67e.bundle.css</exclude> <exclude>dist/styles.f56deed131e58bd7ee04.bundle.css</exclude> <!-- 3rdpartylicenses.txt is an empty file carried along by imported libraries --> <exclude>dist/3rdpartylicenses.txt</exclude> <exclude>e2e/*.js.map</exclude> <!-- Checkstyle is LGPL. We derive ours from their base, but don't ship it, so it's fine use. Since it is derived, we shouldn't get an Apache header --> <exclude>checkstyle.xml</exclude> <!-- Alerts UI e2e test data --> <exclude>e2e/mock-data/alerts_ui_e2e_index.data</exclude> <!-- retry files generated by Ansible during a failure --> <exclude>**/*.retry</exclude> </excludes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-enforcer-plugin</artifactId> <version>1.4.1</version> <executions> <execution> <id>enforce-versions</id> <goals> <goal>enforce</goal> </goals> <configuration> <rules> <requireMavenVersion> <version>${global_maven_version}</version> </requireMavenVersion> <requireJavaVersion> <version>${global_java_version}</version> </requireJavaVersion> </rules> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.17</version> <dependencies> <dependency> <groupId>com.puppycrawl.tools</groupId> <artifactId>checkstyle</artifactId> <version>${global_checkstyle_version}</version> </dependency> </dependencies> <configuration> <configLocation>checkstyle.xml</configLocation> <excludes>**/generated/**/*</excludes> <logViolationsToConsole>false</logViolationsToConsole> </configuration> <executions> <execution> <id>verify</id> <phase>verify</phase> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <distributionManagement> <site> <id>metron</id> <name>Metron</name> <url>file:///tmp/metron/site/</url> </site> </distributionManagement> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> <version>2.3</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.10.4</version> <configuration> <additionalparam>-Xdoclint:none</additionalparam> </configuration> <reportSets> <reportSet> <id>default</id> <reports> <report>javadoc</report> <report>test-javadoc</report> </reports> </reportSet> <reportSet> <id>aggregate</id> <reports> <report>aggregate</report> </reports> </reportSet> </reportSets> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <version>2.9</version> <reportSets> <reportSet> <reports> <!-- Normally, dependency report takes time, skip it --> <!--<report>dependencies</report>--> <report>index</report> <report>cim</report> <report>issue-tracking</report> <report>license</report> <report>mailing-list</report> <report>plugins</report> <report>project-team</report> <report>scm</report> <report>summary</report> </reports> </reportSet> </reportSets> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.17</version> <configuration> <configLocation>checkstyle.xml</configLocation> <excludes>**/generated/**/*</excludes> </configuration> <reportSets> <reportSet> <reports> <report>checkstyle</report> <report>checkstyle-aggregate</report> </reports> </reportSet> </reportSets> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.7.9</version> <reportSets> <reportSet> <reports> <!-- select non-aggregate reports --> <report>report</report> </reports> </reportSet> </reportSets> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>3.7</version> <configuration> <targetJdk>${global_java_version}</targetJdk> </configuration> </plugin> </plugins> </reporting> </project>
{ "content_hash": "5545f380276ae7352dd086cc63252061", "timestamp": "", "source": "github", "line_count": 514, "max_line_length": 128, "avg_line_length": 46.990272373540854, "alnum_prop": 0.4796505610069143, "repo_name": "mattf-horton/metron", "id": "98c942a3ef6cfb63939267487f8a1ed5c4121cb8", "size": "24153", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "12811" }, { "name": "C", "bytes": "49573" }, { "name": "CSS", "bytes": "763669" }, { "name": "HTML", "bytes": "1788682" }, { "name": "Java", "bytes": "5520754" }, { "name": "JavaScript", "bytes": "172067" }, { "name": "Makefile", "bytes": "2579" }, { "name": "Python", "bytes": "269546" }, { "name": "Ruby", "bytes": "19141" }, { "name": "Scala", "bytes": "2700" }, { "name": "Shell", "bytes": "161784" }, { "name": "TypeScript", "bytes": "933459" } ], "symlink_target": "" }
import { TestBed, inject } from '@angular/core/testing'; import { OmicsService } from './omics.service'; describe('OmicsService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [OmicsService] }); }); it('should be created', inject([OmicsService], (service: OmicsService) => { expect(service).toBeTruthy(); })); });
{ "content_hash": "714be2b0a53339ad414f652110cfbffb", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 77, "avg_line_length": 24.533333333333335, "alnum_prop": 0.6304347826086957, "repo_name": "BiRG/Omics-Dashboard", "id": "025dc6003ae54e72414584e181009b477bd55e96", "size": "368", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "omics/workflow-editor/src/app/omics.service.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2625" }, { "name": "Common Workflow Language", "bytes": "11017" }, { "name": "Dockerfile", "bytes": "2078" }, { "name": "HTML", "bytes": "119856" }, { "name": "JavaScript", "bytes": "1716" }, { "name": "Python", "bytes": "686576" }, { "name": "Shell", "bytes": "586" }, { "name": "TypeScript", "bytes": "27794" } ], "symlink_target": "" }
package com.amazonaws.services.identitymanagement.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; /** * */ public class DeleteRoleRequest extends AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the role to delete. * </p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> for this * parameter is a string of characters consisting of upper and lowercase * alphanumeric characters with no spaces. You can also include any of the * following characters: =,.@- * </p> */ private String roleName; /** * <p> * The name of the role to delete. * </p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> for this * parameter is a string of characters consisting of upper and lowercase * alphanumeric characters with no spaces. You can also include any of the * following characters: =,.@- * </p> * * @param roleName * The name of the role to delete.</p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> * for this parameter is a string of characters consisting of upper * and lowercase alphanumeric characters with no spaces. You can also * include any of the following characters: =,.@- */ public void setRoleName(String roleName) { this.roleName = roleName; } /** * <p> * The name of the role to delete. * </p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> for this * parameter is a string of characters consisting of upper and lowercase * alphanumeric characters with no spaces. You can also include any of the * following characters: =,.@- * </p> * * @return The name of the role to delete.</p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> * for this parameter is a string of characters consisting of upper * and lowercase alphanumeric characters with no spaces. You can * also include any of the following characters: =,.@- */ public String getRoleName() { return this.roleName; } /** * <p> * The name of the role to delete. * </p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> for this * parameter is a string of characters consisting of upper and lowercase * alphanumeric characters with no spaces. You can also include any of the * following characters: =,.@- * </p> * * @param roleName * The name of the role to delete.</p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> * for this parameter is a string of characters consisting of upper * and lowercase alphanumeric characters with no spaces. You can also * include any of the following characters: =,.@- * @return Returns a reference to this object so that method calls can be * chained together. */ public DeleteRoleRequest withRoleName(String roleName) { setRoleName(roleName); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRoleName() != null) sb.append("RoleName: " + getRoleName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteRoleRequest == false) return false; DeleteRoleRequest other = (DeleteRoleRequest) obj; if (other.getRoleName() == null ^ this.getRoleName() == null) return false; if (other.getRoleName() != null && other.getRoleName().equals(this.getRoleName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRoleName() == null) ? 0 : getRoleName().hashCode()); return hashCode; } @Override public DeleteRoleRequest clone() { return (DeleteRoleRequest) super.clone(); } }
{ "content_hash": "82a47adb21bfca2d99e0b9aaf4c45f4e", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 80, "avg_line_length": 31.43708609271523, "alnum_prop": 0.5862650094796714, "repo_name": "flofreud/aws-sdk-java", "id": "181c5b60ed80fb061e74eacbd76539981b32ee5c", "size": "5334", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/DeleteRoleRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "126417" }, { "name": "Java", "bytes": "113826096" }, { "name": "Scilab", "bytes": "3561" } ], "symlink_target": "" }
<?php /** * @file * Contains \Drupal\Core\Config\Entity\ConfigEntityDependency. */ namespace Drupal\Core\Config\Entity; /** * Provides a value object to discover configuration dependencies. * * @see \Drupal\Core\Config\Entity\ConfigDependencyManager */ class ConfigEntityDependency { /** * The configuration entity's configuration object name. * * @var string */ protected $name; /** * The configuration entity's dependencies. * * @var array */ protected $dependencies; /** * Constructs the configuration entity dependency from the entity values. * * @param string $name * The configuration entity's configuration object name. * @param array $values * (optional) The configuration entity's values. */ public function __construct($name, $values = array()) { $this->name = $name; if (isset($values['dependencies'])) { $this->dependencies = $values['dependencies']; } else { $this->dependencies = array(); } } /** * Gets the configuration entity's dependencies of the supplied type. * * @param string $type * The type of dependency to return. Either 'module', 'theme', 'config' or * 'content'. * * @return array * The list of dependencies of the supplied type. */ public function getDependencies($type) { $dependencies = array(); if (isset($this->dependencies[$type])) { $dependencies = $this->dependencies[$type]; } if ($type == 'module') { $dependencies[] = substr($this->name, 0, strpos($this->name, '.')); } return $dependencies; } /** * Determines if the entity is dependent on extensions or entities. * * @param string $type * The type of dependency being checked. Either 'module', 'theme', 'config' * or 'content'. * @param string $name * The specific name to check. If $type equals 'module' or 'theme' then it * should be a module name or theme name. In the case of entity it should be * the full configuration object name. * * @return bool */ public function hasDependency($type, $name) { // A config entity is always dependent on its provider. if ($type == 'module' && strpos($this->name, $name . '.') === 0) { return TRUE; } return isset($this->dependencies[$type]) && array_search($name, $this->dependencies[$type]) !== FALSE; } /** * Gets the configuration entity's configuration dependency name. * * @see \Drupal\Core\Entity\EntityInterface::getConfigDependencyName() * * @return string * The configuration dependency name for the entity. */ public function getConfigDependencyName() { return $this->name; } }
{ "content_hash": "98323e6de8f8c8f5c600ceec32f61fef", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 106, "avg_line_length": 26.359223300970875, "alnum_prop": 0.634622467771639, "repo_name": "kaperkin/drupal_8_shelby_site", "id": "9ca55b67f59f749f4d6fcbaa6e1b3146d0f1a5e1", "size": "2715", "binary": false, "copies": "87", "ref": "refs/heads/master", "path": "core/lib/Drupal/Core/Config/Entity/ConfigEntityDependency.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "673" }, { "name": "C++", "bytes": "13011" }, { "name": "CSS", "bytes": "292661" }, { "name": "HTML", "bytes": "319322" }, { "name": "JavaScript", "bytes": "812156" }, { "name": "PHP", "bytes": "26645010" }, { "name": "Shell", "bytes": "41324" } ], "symlink_target": "" }
package nl.mineleni.cbsviewer.util; import java.io.File; import java.net.URL; import java.util.Collections; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import nl.mineleni.cbsviewer.util.xml.LayerDescriptor; import nl.mineleni.cbsviewer.util.xml.LayersList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import flexjson.JSONSerializer; import flexjson.transformer.AbstractTransformer; /** * AvailableLayersBean maakt de beschikbare kaarten bekend in de applicatie op * basis van het xml configuratie bestand {@code AvailableLayers.xml}. * * @author mprins * @since 1.6 * * @composed 1 - 1..* LayerDescriptor * @depend - layersList - LayersList */ public class AvailableLayersBean { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory .getLogger(AvailableLayersBean.class); /** * lijst met beschikbare layers. */ private List<LayerDescriptor> layers = null; /** * default constructor. */ public AvailableLayersBean() { try { final JAXBContext jc = JAXBContext .newInstance("nl.mineleni.cbsviewer.util.xml"); final Unmarshaller u = jc.createUnmarshaller(); final URL r = this.getClass().getClassLoader() .getResource("AvailableLayers.xml"); if (r != null) { final File f = new File(r.getFile()); @SuppressWarnings("unchecked") final JAXBElement<LayersList> element = (JAXBElement<LayersList>) u .unmarshal(f); final LayersList layerslist = element.getValue(); this.layers = layerslist.getLayerdescriptor(); } else { throw new JAXBException( "Bestand 'AvailableLayers.xml' niet gevonden"); } } catch (final JAXBException e) { LOGGER.error( "Er is een fout opgetreden bij het inlezen van de layers.", e); } } /** * accessor voor de lijst met layers. * * @return geeft de lijst van LayerDescriptors voor de applicatie */ public List<LayerDescriptor> getLayers() { return Collections.unmodifiableList(this.layers); } /** * Geeft de kaarten als javascript variabele. * * @return layers als json object * @see #asJSON(boolean) */ public String asJSON() { return this.asJSON(true); } /** * Geeft de kaarten als json object ({@code asVar == false}) of javascript * variabele, ingepakt in een CDATA sectie. Het object is een array met * LayerDescriptors. Null waarden worden niet geserialiseerd, hierdoor zijn * objecten niet round-trip serialiseerbaar (dus equals() niet bruikbaar). * * @param asVar * {@code true} als er een javascript variabele moet worden * gegeven. * @return layers als json * * @see #asJSON() */ public String asJSON(final boolean asVar) { final JSONSerializer serializer = new JSONSerializer(); final String json = serializer.transform(new AbstractTransformer() { @Override public Boolean isInline() { return true; } @Override public void transform(final Object object) { // null objecten niet serializeren. return; } }, void.class).exclude("class", "aliases", "attributes") .prettyPrint(LOGGER.isDebugEnabled()).serialize(this.layers); if (asVar) { return "\n/* <![CDATA[ */ var _layers=" + json + ";/* ]]> */"; } return json; } /** * geeft de eerste layerdescriptor met de gevraagde id. * * @param id * de ID van de laag * @return the layer by id * @see LayerDescriptor#getId() */ public LayerDescriptor getLayerByID(final String id) { for (final LayerDescriptor desc : this.layers) { if (desc.getId().equalsIgnoreCase(id)) { return desc; } } return null; } /** * geeft de eerste layerdescriptor met de gevraagde naam. * * @param queryLyrName * de naam van de wms laag * @param lyrUrl * de url van de wms * * @return the layer by name and url * @see LayerDescriptor#getLayers() */ public LayerDescriptor getLayerByLayers(final String queryLyrName, final String lyrUrl) { for (final LayerDescriptor desc : this.layers) { if ((desc.getLayers().replaceAll("\\s", "")) .equalsIgnoreCase(queryLyrName.replaceAll("\\s", ""))) { if (desc.getUrl().equalsIgnoreCase(lyrUrl)) { LOGGER.debug("Gevonden layer-id is: " + desc.getId()); return desc; } } } return null; } /** * geeft de eerste layerdescriptor met de gevraagde naam, url en styles. * * @param queryLyrName * de naam van de wms laag * @param lyrUrl * de url van de wms * @param styles * wms styles * * @return the layer by name and url * @see LayerDescriptor#getLayers() */ public LayerDescriptor getLayerByLayers(final String queryLyrName, final String lyrUrl, final String styles) { for (final LayerDescriptor desc : this.layers) { if ((desc.getLayers().replaceAll("\\s", "")) .equalsIgnoreCase(queryLyrName.replaceAll("\\s", ""))) { if (desc.getUrl().equalsIgnoreCase(lyrUrl)) { if (desc.getStyles().replaceAll("\\s", "") .equalsIgnoreCase(styles)) { LOGGER.debug("Gevonden layer-id is: " + desc.getId()); return desc; } } } } return null; } /** * geeft de eerste layerdescriptor met de gevraagde naam. * * @param name * de naam van de laag * @return the layer by name * @see LayerDescriptor#getName() */ public LayerDescriptor getLayerByName(final String name) { for (final LayerDescriptor desc : this.layers) { if (desc.getName().equalsIgnoreCase(name)) { LOGGER.debug("Gevonden layer-id is: " + desc.getId()); return desc; } } return null; } }
{ "content_hash": "29cfa4901071811e8d261eb8327eba6e", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 78, "avg_line_length": 27.093457943925234, "alnum_prop": 0.6590203518454639, "repo_name": "mprins/CBSviewer", "id": "f9bb66cf2cba4a0a91336d03528010956e716646", "size": "6038", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/nl/mineleni/cbsviewer/util/AvailableLayersBean.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "38472" }, { "name": "Game Maker Language", "bytes": "35633" }, { "name": "HTML", "bytes": "7178" }, { "name": "Java", "bytes": "531411" }, { "name": "JavaScript", "bytes": "261555" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_31) on Wed Dec 17 20:48:24 PST 2014 --> <title>Uses of Class java.awt.image.ComponentSampleModel (Java Platform SE 8 )</title> <meta name="date" content="2014-12-17"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class java.awt.image.ComponentSampleModel (Java Platform SE 8 )"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../java/awt/image/ComponentSampleModel.html" title="class in java.awt.image">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;8</strong></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?java/awt/image/class-use/ComponentSampleModel.html" target="_top">Frames</a></li> <li><a href="ComponentSampleModel.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class java.awt.image.ComponentSampleModel" class="title">Uses of Class<br>java.awt.image.ComponentSampleModel</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../java/awt/image/ComponentSampleModel.html" title="class in java.awt.image">ComponentSampleModel</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#java.awt.image">java.awt.image</a></td> <td class="colLast"> <div class="block">Provides classes for creating and modifying images.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="java.awt.image"> <!-- --> </a> <h3>Uses of <a href="../../../../java/awt/image/ComponentSampleModel.html" title="class in java.awt.image">ComponentSampleModel</a> in <a href="../../../../java/awt/image/package-summary.html">java.awt.image</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../java/awt/image/ComponentSampleModel.html" title="class in java.awt.image">ComponentSampleModel</a> in <a href="../../../../java/awt/image/package-summary.html">java.awt.image</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../java/awt/image/BandedSampleModel.html" title="class in java.awt.image">BandedSampleModel</a></span></code> <div class="block">This class represents image data which is stored in a band interleaved fashion and for which each sample of a pixel occupies one data element of the DataBuffer.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../java/awt/image/PixelInterleavedSampleModel.html" title="class in java.awt.image">PixelInterleavedSampleModel</a></span></code> <div class="block">This class represents image data which is stored in a pixel interleaved fashion and for which each sample of a pixel occupies one data element of the DataBuffer.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../java/awt/image/ComponentSampleModel.html" title="class in java.awt.image">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;8</strong></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?java/awt/image/class-use/ComponentSampleModel.html" target="_top">Frames</a></li> <li><a href="ComponentSampleModel.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://download.oracle.com/javase/8/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../legal/cpyr.html">Copyright</a> &#x00a9; 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p> </body> </html>
{ "content_hash": "b65b2462a27f31668e0d27fc0c649f0d", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 603, "avg_line_length": 42.51933701657459, "alnum_prop": 0.656964656964657, "repo_name": "fbiville/annotation-processing-ftw", "id": "617ac52c50cc71e22322910ffe4e4858415da6f9", "size": "7696", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/java/jdk8/java/awt/image/class-use/ComponentSampleModel.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "191178" }, { "name": "HTML", "bytes": "63904" }, { "name": "Java", "bytes": "107042" }, { "name": "JavaScript", "bytes": "246677" } ], "symlink_target": "" }
package android.text; import java.lang.reflect.Array; import java.util.Arrays; /** * A cached set of spans. Caches the result of {@link Spanned#getSpans(int, int, Class)} and then * provides faster access to {@link Spanned#nextSpanTransition(int, int, Class)}. * * Fields are left public for a convenient direct access. * * Note that empty spans are ignored by this class. * @hide */ public class SpanSet<E> { private final Class<? extends E> classType; int numberOfSpans; E[] spans; int[] spanStarts; int[] spanEnds; int[] spanFlags; SpanSet(Class<? extends E> type) { classType = type; numberOfSpans = 0; } @SuppressWarnings("unchecked") public void init(Spanned spanned, int start, int limit) { final E[] allSpans = spanned.getSpans(start, limit, classType); final int length = allSpans.length; if (length > 0 && (spans == null || spans.length < length)) { // These arrays may end up being too large because of the discarded empty spans spans = (E[]) Array.newInstance(classType, length); spanStarts = new int[length]; spanEnds = new int[length]; spanFlags = new int[length]; } int prevNumberOfSpans = numberOfSpans; numberOfSpans = 0; for (int i = 0; i < length; i++) { final E span = allSpans[i]; final int spanStart = spanned.getSpanStart(span); final int spanEnd = spanned.getSpanEnd(span); if (spanStart == spanEnd) continue; final int spanFlag = spanned.getSpanFlags(span); spans[numberOfSpans] = span; spanStarts[numberOfSpans] = spanStart; spanEnds[numberOfSpans] = spanEnd; spanFlags[numberOfSpans] = spanFlag; numberOfSpans++; } // cleanup extra spans left over from previous init() call if (numberOfSpans < prevNumberOfSpans) { // prevNumberofSpans was > 0, therefore spans != null Arrays.fill(spans, numberOfSpans, prevNumberOfSpans, null); } } /** * Returns true if there are spans intersecting the given interval. * @param end must be strictly greater than start */ public boolean hasSpansIntersecting(int start, int end) { for (int i = 0; i < numberOfSpans; i++) { // equal test is valid since both intervals are not empty by construction if (spanStarts[i] >= end || spanEnds[i] <= start) continue; return true; } return false; } /** * Similar to {@link Spanned#nextSpanTransition(int, int, Class)} */ int getNextTransition(int start, int limit) { for (int i = 0; i < numberOfSpans; i++) { final int spanStart = spanStarts[i]; final int spanEnd = spanEnds[i]; if (spanStart > start && spanStart < limit) limit = spanStart; if (spanEnd > start && spanEnd < limit) limit = spanEnd; } return limit; } /** * Removes all internal references to the spans to avoid memory leaks. */ public void recycle() { if (spans != null) { Arrays.fill(spans, 0, numberOfSpans, null); } } }
{ "content_hash": "57ce84482f64626bbf3247dc59e32c5c", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 97, "avg_line_length": 31.692307692307693, "alnum_prop": 0.5925364077669902, "repo_name": "daiqiquan/framework-base", "id": "00f14939a7ad280d69e148148794cff5dfc5f055", "size": "3915", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "core/java/android/text/SpanSet.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "10239" }, { "name": "C++", "bytes": "3841417" }, { "name": "GLSL", "bytes": "1500" }, { "name": "HTML", "bytes": "196467" }, { "name": "Java", "bytes": "56796292" }, { "name": "Makefile", "bytes": "103735" }, { "name": "Shell", "bytes": "423" } ], "symlink_target": "" }
"""Module to handle /pkgs""" import logging import urllib from google.appengine.api import memcache from google.appengine.ext import blobstore from google.appengine.ext.webapp import blobstore_handlers from simian.auth import gaeserver from simian.mac import models from simian.mac.common import auth from simian.mac.munki import common from simian.mac.munki import handlers def PackageExists(filename): """Check whether a package exists. Args: filename: str, package filename like 'foo.dmg' Returns: True or False """ return models.PackageInfo.get_by_key_name(filename) is not None class Packages( handlers.AuthenticationHandler, blobstore_handlers.BlobstoreDownloadHandler): """Handler for /pkgs/""" def get(self, filename): """GET Args: filename: str, package filename like 'foo.dmg' Returns: None if a blob is being returned, or a response object """ auth_return = auth.DoAnyAuth() if hasattr(auth_return, 'email'): email = auth_return.email() if not auth.IsAdminUser(email) and not auth.IsSupportUser(email): raise auth.IsAdminMismatch filename = urllib.unquote(filename) pkg = models.PackageInfo.MemcacheWrappedGet(filename) if pkg is None or not pkg.blobstore_key: self.error(404) return if common.IsPanicModeNoPackages(): self.error(503) return # Get the Blobstore BlobInfo for this package; memcache wrapped. memcache_key = 'blobinfo_%s' % filename blob_info = memcache.get(memcache_key) if not blob_info: blob_info = blobstore.BlobInfo.get(pkg.blobstore_key) if blob_info: memcache.set(memcache_key, blob_info, 300) # cache for 5 minutes. else: logging.critical( 'Failure fetching BlobInfo for %s. Verify the blob exists: %s', pkg.filename, pkg.blobstore_key) self.error(404) return header_date_str = self.request.headers.get('If-Modified-Since', '') etag_nomatch_str = self.request.headers.get('If-None-Match', 0) etag_match_str = self.request.headers.get('If-Match', 0) pkg_date = blob_info.creation pkg_size_bytes = blob_info.size # TODO(user): The below can be simplified once all of our clients # have ETag values set on the filesystem for these files. The # parsing of If-Modified-Since could be removed. Removing it prematurely # will cause a re-download of all packages on all clients for 1 iteration # until they all have ETag values. # Reduce complexity of elif conditional below. # If an If-None-Match: ETag is supplied, don't worry about a # missing file modification date -- the ETag supplies everything needed. if etag_nomatch_str and not header_date_str: resource_expired = False else: resource_expired = handlers.IsClientResourceExpired( pkg_date, header_date_str) # Client supplied If-Match: etag, but that etag does not match current # etag. return 412. if (etag_match_str and pkg.pkgdata_sha256 and etag_match_str != pkg.pkgdata_sha256): self.response.set_status(412) # Client supplied no etag or If-No-Match: etag, and the etag did not # match, or the client's file is older than the mod time of this package. elif ((etag_nomatch_str and pkg.pkgdata_sha256 and etag_nomatch_str != pkg.pkgdata_sha256) or resource_expired): self.response.headers['Content-Disposition'] = str( 'attachment; filename=%s' % filename) # header date empty or package has changed, send blob with last-mod date. if pkg.pkgdata_sha256: self.response.headers['ETag'] = str(pkg.pkgdata_sha256) self.response.headers['Last-Modified'] = pkg_date.strftime( handlers.HEADER_DATE_FORMAT) self.response.headers['X-Download-Size'] = str(pkg_size_bytes) self.send_blob(pkg.blobstore_key) else: # Client doesn't need to do anything, current version is OK based on # ETag and/or last modified date. if pkg.pkgdata_sha256: self.response.headers['ETag'] = str(pkg.pkgdata_sha256) self.response.set_status(304) class ClientRepair(Packages): """Handler for /repair/""" def get(self, client_id_str=''): """GET Returns: None if a blob is being returned, or a response object """ session = auth.DoAnyAuth() client_id = handlers.GetClientIdForRequest( self.request, session=session, client_id_str=client_id_str) logging.info('Repair client ID: %s', client_id) filename = None for pkg in models.PackageInfo.all().filter('name =', 'munkitools'): if client_id.get('track', '') in pkg.catalogs: filename = pkg.filename break if filename: logging.info('Sending client: %s', filename) super(ClientRepair, self).get(filename) else: logging.warning('No repair client found.')
{ "content_hash": "5962d0e962e42ada97c40999b8f2432b", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 79, "avg_line_length": 33.317567567567565, "alnum_prop": 0.6779557899006287, "repo_name": "alexandregz/simian", "id": "048d547002924483106c58492329c3fed0adcc7d", "size": "5556", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/simian/mac/munki/handlers/pkgs.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "37847" }, { "name": "HTML", "bytes": "89696" }, { "name": "JavaScript", "bytes": "28084" }, { "name": "Makefile", "bytes": "8128" }, { "name": "Python", "bytes": "1431095" }, { "name": "Shell", "bytes": "19945" } ], "symlink_target": "" }
<?php namespace App\Http\Controllers\AdminAuth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Foundation\Auth\ResetsPasswords; class PasswordController extends Controller { /* |-------------------------------------------------------------------------- | Password Reset Controller |-------------------------------------------------------------------------- | | This controller is responsible for handling password reset requests | and uses a simple trait to include this behavior. You're free to | explore this trait and override any methods you wish to tweak. | */ use ResetsPasswords; protected $guard = 'admin'; protected $broker = 'admins'; /** * Create a new password controller instance. * * @return void */ public function __construct() { $this->middleware('guest:admin'); } public function getEmail() { return $this->showLinkRequestForm(); } public function showLinkRequestForm() { if (property_exists($this, 'linkRequestView')) { return view($this->linkRequestView); } if (view()->exists('admin.auth.passwords.email')) { return view('admin.auth.passwords.email'); } return view('admin.auth.password'); } public function showResetForm(Request $request, $token = null) { if (is_null($token)) { return $this->getEmail(); } $email = $request->input('email'); if (property_exists($this, 'resetView')) { return view($this->resetView)->with(compact('token', 'email')); } if (view()->exists('admin.auth.passwords.reset')) { return view('admin.auth.passwords.reset')->with(compact('token', 'email')); } return view('admin.passwords.auth.reset')->with(compact('token', 'email')); } }
{ "content_hash": "2608cf7bf5cf60832356fab23e3b0a52", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 87, "avg_line_length": 26.175675675675677, "alnum_prop": 0.5539494062983996, "repo_name": "nitishdola/material-management-systems", "id": "7a0447bb6941832ef52d251e0768b81f5c4d4c2f", "size": "1937", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "app/Http/Controllers/DepartmentUserAuth/PasswordController.php", "mode": "33261", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "15982" }, { "name": "CSS", "bytes": "125422" }, { "name": "HTML", "bytes": "2921986" }, { "name": "JavaScript", "bytes": "2317865" }, { "name": "Makefile", "bytes": "902" }, { "name": "PHP", "bytes": "982769" }, { "name": "Shell", "bytes": "342" }, { "name": "Smarty", "bytes": "60924" } ], "symlink_target": "" }
"""The component for STIEBEL ELTRON heat pumps with ISGWeb Modbus module.""" from datetime import timedelta import logging from pystiebeleltron import pystiebeleltron import voluptuous as vol from homeassistant.components.modbus import ( CONF_HUB, DEFAULT_HUB, DOMAIN as MODBUS_DOMAIN, ) from homeassistant.const import CONF_NAME, DEVICE_DEFAULT_NAME, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType from homeassistant.util import Throttle DOMAIN = "stiebel_eltron" CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional(CONF_NAME, default=DEVICE_DEFAULT_NAME): cv.string, vol.Optional(CONF_HUB, default=DEFAULT_HUB): cv.string, } ) }, extra=vol.ALLOW_EXTRA, ) _LOGGER = logging.getLogger(__name__) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30) def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the STIEBEL ELTRON unit. Will automatically load climate platform. """ name = config[DOMAIN][CONF_NAME] modbus_client = hass.data[MODBUS_DOMAIN][config[DOMAIN][CONF_HUB]] hass.data[DOMAIN] = { "name": name, "ste_data": StiebelEltronData(name, modbus_client), } discovery.load_platform(hass, Platform.CLIMATE, DOMAIN, {}, config) return True class StiebelEltronData: """Get the latest data and update the states.""" def __init__(self, name, modbus_client): """Init the STIEBEL ELTRON data object.""" self.api = pystiebeleltron.StiebelEltronAPI(modbus_client, 1) @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Update unit data.""" if not self.api.update(): _LOGGER.warning("Modbus read failed") else: _LOGGER.debug("Data updated successfully")
{ "content_hash": "36c618a7acef8397ba181bb96b58d74c", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 80, "avg_line_length": 28.271428571428572, "alnum_prop": 0.6796361798888327, "repo_name": "mezz64/home-assistant", "id": "84a39e3c87598cbcf19613ec7776e79f01933f01", "size": "1979", "binary": false, "copies": "3", "ref": "refs/heads/dev", "path": "homeassistant/components/stiebel_eltron/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2963" }, { "name": "PLSQL", "bytes": "840" }, { "name": "Python", "bytes": "52481895" }, { "name": "Shell", "bytes": "6252" } ], "symlink_target": "" }
/* This work is licensed under the Creative Commons Attribution-NonCommercial 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/3.0/. */ /*** Created By Isaac Wheeler */ package Json; import java.util.List; public class InstallInfo { public String Config; private List<forge> Forge; private List<version> version; private List<mods> mods; @Override public String toString() { return "DataObject " + version() + mods + ""; } public List<version> version() { return version; } public List<mods> mods() { return mods; } public String Config(){ return Config; } public List<forge> forge(){ return Forge; } }
{ "content_hash": "fe27d55365c6154fe6524e664f42a090", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 85, "avg_line_length": 16.232558139534884, "alnum_prop": 0.6919770773638968, "repo_name": "PAQ-MC/PAQ-Config-Genrator", "id": "1cbc0a1a2c69b6bc69e90455dfb269e2b41f0634", "size": "698", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Json/InstallInfo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "13405" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>stalmarck: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.14.1 / stalmarck - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> stalmarck <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-07-19 14:49:40 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-07-19 14:49:40 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.14.1 Formal proof management system dune 3.3.1 Fast, portable, and opinionated build system ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler ocamlfind 1.9.1 A library manager for OCaml ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-community/stalmarck&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Stalmarck&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: boolean formula&quot; &quot;keyword: tautology checker&quot; &quot;category: Computer Science/Decision Procedures and Certified Algorithms/Decision procedures&quot; &quot;category: Miscellaneous/Extracted Programs/Decision procedures&quot; &quot;date: 2000&quot; ] authors: [ &quot;Pierre Letouzey&quot; &quot;Laurent Théry&quot; ] bug-reports: &quot;https://github.com/coq-community/stalmarck/issues&quot; dev-repo: &quot;git+https://github.com/coq-community/stalmarck.git&quot; synopsis: &quot;Proof of Stalmarck&#39;s algorithm&quot; description: &quot;&quot;&quot; A two-level approach to prove tautology using Stalmarck&#39;s algorithm.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-community/stalmarck/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=5d5b5316fd65d219d53014f465dfa340&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-stalmarck.8.6.0 coq.8.14.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.14.1). The following dependencies couldn&#39;t be met: - coq-stalmarck -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-stalmarck.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "23d2fe31d103698e8f2a6abd756fa7e2", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 287, "avg_line_length": 43.595238095238095, "alnum_prop": 0.5492900054614964, "repo_name": "coq-bench/coq-bench.github.io", "id": "f74e3c574086b33bc0922abbf6d271a47511a7ad", "size": "7350", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.14.1/stalmarck/8.6.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/* Steps to make your tables sortable: - Set the class of your table to "tablesort" (no other classnames allowed) - Optional: set the class of TH to "sortnum" for numeric columns - Add tablesort.js to your page and call TS.init() when the table is present You can add tablesort.js asynchronously this way: var script = document.createElement('script'); script.src = "tablesort.js"; script.onload = function() { TS.init(); }; document.getElementsByTagName('head')[0].appendChild(script); */ var TS = {}; TS.bIE = ( -1 != navigator.userAgent.indexOf("MSIE")); TS.init = function() { var aTables = document.getElementsByTagName('table'); var len = aTables.length; for ( var i = 0; i < len; i++ ) { var table = aTables[i]; if ( TS.isSortable(table) ) { TS.tableAddSort(table); } } }; TS.tableAddSort = function(table) { var thead = TS.getThead(table); var aThs = thead.getElementsByTagName('th'); var len = aThs.length; for ( var i = 0; i < len; i++ ) { var th = aThs[i]; if ( ! TS.dontSort(th) ) { TS.thAddSort(th); } } }; TS.getThead = function(table) { var thead = table.getElementsByTagName('thead')[0]; if ( ! thead ) { thead = document.createElement('thead'); thead.appendChild(table.rows[0]); table.insertBefore(thead, table.firstChild); } thead.onmouseout = function(e) { TS.hideSort(e); }; return thead; }; TS.thAddSort = function(th) { th.onmouseover = function() { TS.showSort(th); }; }; TS.hideSort = function(event) { var tsdivup = document.getElementById('tsdivup'); var tsdivdn = document.getElementById('tsdivdn'); if ( tsdivup ) { if ( ! event ) { event = window.event; } var target = ( (window.event) ? event.srcElement : event.target ); if ( 'TH' != target.nodeName ) { return; } // Due to event bubbling, we have to make sure the mouse is actually outside of // the TH including the "sortlink"s. See http://www.quirksmode.org/js/events_mouse.html. var relTarget = (event.relatedTarget) ? event.relatedTarget : event.toElement; while ( target != relTarget && "sortlink" != relTarget.className && "BODY" != relTarget.nodeName ) { relTarget = relTarget.parentNode; } if ( relTarget == target || "sortlink" === relTarget.className ) { return; } // OK - actually hide it now tsdivup.style.display = "none"; tsdivdn.style.display = "none"; } }; TS.showSort = function(th) { var tsdivup = document.getElementById('tsdivup'); var tsdivdn = document.getElementById('tsdivdn'); TS.curTH = th; // dangerous if ( ! tsdivup ) { tsdivup = TS.makeTsdiv(); tsdivup.id = "tsdivup"; tsdivup.innerHTML = "<a class='sortlink' title='z-a' style='border: 0; outline: 0; text-decoration: none; color: #00F;' href='#sort z-a' onclick='TS.sortCba(); return false;'>" + ( TS.bIE ? '<font face="webdings">5</font>' : '&#x25B4;' ) + "</a>"; document.body.appendChild(tsdivup); tsdivup.saveW = tsdivup.clientWidth; tsdivup.saveH = tsdivup.clientHeight; tsdivdn = TS.makeTsdiv(); tsdivdn.id = "tsdivdn"; tsdivdn.innerHTML = "<a class='sortlink' title='a-z' style='border: 0; outline: 0; text-decoration: none; color: #00F;' href='#sort a-z' onclick='TS.sortAbc(); return false;'>" + ( TS.bIE ? '<font face="webdings">6</font>' : '&#x25BE;' ) + "</a>"; document.body.appendChild(tsdivdn); // Once we set the display to "none" the client dimensions turn to zero. // So we save the client dimensions for left & top calculations below. tsdivdn.saveW = tsdivdn.clientWidth; tsdivdn.saveH = tsdivdn.clientHeight; } var aPosition = TS.findPos(th); tsdivup.style.left = (aPosition[0]+(th.clientWidth-tsdivup.saveW)) + "px"; tsdivup.style.top = (aPosition[1]) + "px"; tsdivup.style.display = "block"; tsdivdn.style.left = (aPosition[0]+(th.clientWidth-tsdivdn.saveW)) + "px"; tsdivdn.style.top = (aPosition[1]+(th.clientHeight-tsdivdn.saveH)) + "px"; tsdivdn.style.display = "block"; }; TS.makeTsdiv = function() { var tsdiv = document.createElement('div'); tsdiv.style.position = "absolute"; tsdiv.style.backgroundColor = "white"; tsdiv.style.fontSize = "14pt"; return tsdiv; }; TS.sortAbc = function(elem) { TS.sort(elem, 0); }; TS.sortCba = function(elem) { TS.sort(elem, 1); }; TS.sort = function(elem, bCba) { // TODO - The cursor doesn't change. Is the loop too tight? //document.body.style.cursor = "wait"; var th = TS.curTH; var table = TS.findParentByTagName(th, 'table'); if ( !table || !th ) { return; } // find the column # var aThs = table.getElementsByTagName('th'); var len = aThs.length; var iCol; var iTd = 0; for ( var i = 0; i < len; i++ ) { if ( th == aThs[i] ) { iCol = iTd; break; } iTd += aThs[i].colSpan; } if ( "undefined" === typeof(iCol) ) { return; } TS.sortTable(table, iCol, bCba, th.className); //document.body.style.cursor = ""; }; TS.sortTable = function(table, iCol, bCba, sortType) { var row_array = []; var tbody = table.tBodies[0]; var rows = tbody.rows; var len = rows.length; for ( var iRow=0; iRow < len; iRow++) { row_array.push( [ TS.getText(rows[iRow].cells[iCol], sortType), rows[iRow] ] ); } row_array.sort(bCba ? TS.sortfuncCba : TS.sortfuncAbc ); len = row_array.length; for ( var iRow=0; iRow < len; iRow++ ) { var row = row_array[iRow][1]; row.className = ( 0 === (iRow % 2) ? "odd" : "even" ); tbody.appendChild(row); } delete row_array; }; TS.getText = function(cell, sortType) { var text = ( "undefined" != typeof(cell.textContent) ? cell.textContent : ( "undefined" != typeof(cell.innerText) ? cell.innerText : ( "undefined" != typeof(cell.text) ? cell.text : cell.innerHTML ) ) ); if ( "sortnum" === sortType ) { text = parseInt(text); } return text; }; TS.sortfuncAbc = function(a, b) { if ( a[0] == b[0] ) { return 0; } if ( a[0] < b[0] ) { return -1; } return 1; }; TS.sortfuncCba = function(a, b) { return ( TS.sortfuncAbc(a, b) * (-1) ); }; TS.findParentByTagName = function(elem, tagname) { tagname = tagname.toLowerCase(); while ( elem.parentNode ) { if ( tagname === elem.parentNode.tagName.toLowerCase() ) { return elem.parentNode; } elem = elem.parentNode; } return undefined; }; TS.isSortable = function(th) { return ( "tablesort" === th.className ); }; TS.dontSort = function(th) { return ( "notablesort" === th.className ); }; // from http://www.quirksmode.org/js/findpos.html TS.findPos = function(obj) { var curleft = curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return [curleft,curtop]; };
{ "content_hash": "cfd8bab43d906525258fc67ff364d614", "timestamp": "", "source": "github", "line_count": 262, "max_line_length": 181, "avg_line_length": 25.33587786259542, "alnum_prop": 0.6434166917746309, "repo_name": "marcelduran/httparchive", "id": "8e07d7360d7edb1a8821e23123651a401dd2212c", "size": "7196", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tablesort.js", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
@implementation ArtUIStyleManager (UIStyleModule3) - (NSString *)getStyleName_Module3 { return @"Module3Style.plist"; } - (NSString *)getHotReloaderStylePath_Module3 { return @"/App/Module3/UIStyle/Module3Style.plist"; } @end @implementation UIColor (UIStyleModule3) + (UIColor *)artModule3ForKey:(NSString *)aColorKey { return [self artModule:@"Module3" colorForKey:aColorKey]; } + (void)artModule3ForKey:(NSString *)aColorKey strongSelf:(id)strongSelf block:(void(^)(UIColor *color, id weakSelf))aBlock { [self artModule:@"Module3" colorForKey:aColorKey strongSelf:strongSelf block:aBlock]; } @end @implementation UIFont (UIStyleCourseware) + (UIFont *)artModule3ForKey:(NSString *)aFontKey { return [self artModule:@"Module3" fontForKey:aFontKey]; } + (void)artModule3ForKey:(NSString *)aFontKey strongSelf:(id)strongSelf block:(void(^)(UIFont *color, id weakSelf))aBlock { [self artModule:@"Module3" fontForKey:aFontKey strongSelf:strongSelf block:aBlock]; } @end
{ "content_hash": "633e790c35e007ae9e0063db862860f5", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 125, "avg_line_length": 27.88888888888889, "alnum_prop": 0.749003984063745, "repo_name": "weijingyunIOS/ArtChangeTheme", "id": "97341caabf1febe41a308b1bfbb6158a5d255297", "size": "1239", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ChangeTheme_OC/ChangeTheme_OC/App/Module3/UIStyle/ArtUIStyleManager+UIStyleModule3.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "334421" }, { "name": "C++", "bytes": "28031" }, { "name": "Objective-C", "bytes": "19297" }, { "name": "Ruby", "bytes": "401" }, { "name": "Shell", "bytes": "17196" }, { "name": "Swift", "bytes": "133462" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>Lighthouse: lapack/chetrs2.f File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="tabs.css" rel="stylesheet" type="text/css" /> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <!--<div id="titlearea"> </div>--> <!-- end header part --> <!-- Generated by Doxygen 1.8.2 --> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_42b7da8b2ebcfce3aea4b69198a0a9ad.html">lapack</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#func-members">Functions/Subroutines</a> </div> <div class="headertitle"> <div class="title">chetrs2.f File Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions/Subroutines</h2></td></tr> <tr class="memitem:aaa17e6b0561b20ce0353882d8964504c"><td class="memItemLeft" align="right" valign="top">subroutine&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="chetrs2_8f.html#aaa17e6b0561b20ce0353882d8964504c">chetrs2</a> (UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, INFO)</td></tr> <tr class="memdesc:aaa17e6b0561b20ce0353882d8964504c"><td class="mdescLeft">&#160;</td><td class="mdescRight"><b>CHETRS2</b> <a href="#aaa17e6b0561b20ce0353882d8964504c"></a><br/></td></tr> <tr class="separator:aaa17e6b0561b20ce0353882d8964504c"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Function/Subroutine Documentation</h2> <a class="anchor" id="aaa17e6b0561b20ce0353882d8964504c"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">subroutine chetrs2 </td> <td>(</td> <td class="paramtype">character&#160;</td> <td class="paramname"><em>UPLO</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>N</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>NRHS</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">complex, dimension( lda, * )&#160;</td> <td class="paramname"><em>A</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>LDA</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer, dimension( * )&#160;</td> <td class="paramname"><em>IPIV</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">complex, dimension( ldb, * )&#160;</td> <td class="paramname"><em>B</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>LDB</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">complex, dimension( * )&#160;</td> <td class="paramname"><em>WORK</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>INFO</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p><b>CHETRS2</b> </p> Download CHETRS2 + dependencies <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/chetrs2.f"> [TGZ]</a> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/chetrs2.f"> [ZIP]</a> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/chetrs2.f"> [TXT]</a> <dl class="section user"><dt>Purpose: </dt><dd><pre class="fragment"> CHETRS2 solves a system of linear equations A*X = B with a complex Hermitian matrix A using the factorization A = U*D*U**H or A = L*D*L**H computed by CHETRF and converted by CSYCONV.</pre> </dd></dl> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramdir">[in]</td><td class="paramname">UPLO</td><td><pre class="fragment"> UPLO is CHARACTER*1 Specifies whether the details of the factorization are stored as an upper or lower triangular matrix. = 'U': Upper triangular, form is A = U*D*U**H; = 'L': Lower triangular, form is A = L*D*L**H.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">N</td><td><pre class="fragment"> N is INTEGER The order of the matrix A. N &gt;= 0.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">NRHS</td><td><pre class="fragment"> NRHS is INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS &gt;= 0.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">A</td><td><pre class="fragment"> A is COMPLEX array, dimension (LDA,N) The block diagonal matrix D and the multipliers used to obtain the factor U or L as computed by CHETRF.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">LDA</td><td><pre class="fragment"> LDA is INTEGER The leading dimension of the array A. LDA &gt;= max(1,N).</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">IPIV</td><td><pre class="fragment"> IPIV is INTEGER array, dimension (N) Details of the interchanges and the block structure of D as determined by CHETRF.</pre></td></tr> <tr><td class="paramdir">[in,out]</td><td class="paramname">B</td><td><pre class="fragment"> B is COMPLEX array, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">LDB</td><td><pre class="fragment"> LDB is INTEGER The leading dimension of the array B. LDB &gt;= max(1,N).</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">WORK</td><td><pre class="fragment"> WORK is COMPLEX array, dimension (N)</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">INFO</td><td><pre class="fragment"> INFO is INTEGER = 0: successful exit &lt; 0: if INFO = -i, the i-th argument had an illegal value</pre> </td></tr> </table> </dd> </dl> <dl class="section author"><dt>Author</dt><dd>Univ. of Tennessee </dd> <dd> Univ. of California Berkeley </dd> <dd> Univ. of Colorado Denver </dd> <dd> NAG Ltd. </dd></dl> <dl class="section date"><dt>Date</dt><dd>November 2011 </dd></dl> </div> </div> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Jul 14 2014 18:28:48 for Lighthouse by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.2 </small></address> </body> </html>
{ "content_hash": "2d3a42dde96b0e0be26b45f817fdcfe3", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 309, "avg_line_length": 46.51149425287356, "alnum_prop": 0.5895218089707155, "repo_name": "LighthouseHPC/lighthouse", "id": "24e457706b4e081792adb3e8dc1b70b1f2fe3a7e", "size": "8093", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Dlighthouse/media/Doxygen/docs/html/chetrs2_8f.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import '../gr-range-header/gr-range-header'; import {CommentRange} from '../../../types/common'; import {LitElement, css, html} from 'lit'; import {customElement, property} from 'lit/decorators.js'; import {sharedStyles} from '../../../styles/shared-styles'; import {grRangedCommentTheme} from '../gr-ranged-comment-themes/gr-ranged-comment-theme'; @customElement('gr-ranged-comment-hint') export class GrRangedCommentHint extends LitElement { @property({type: Object}) range?: CommentRange; static override get styles() { return [ grRangedCommentTheme, sharedStyles, css` .row { display: flex; --gr-range-header-color: var(--ranged-comment-hint-text-color); } gr-range-header { flex-grow: 1; } `, ]; } override render() { return html`<div class="rangeHighlight row"> <gr-range-header icon="mode_comment" filled >${this._computeRangeLabel(this.range)}</gr-range-header > </div>`; } _computeRangeLabel(range?: CommentRange): string { if (!range) return ''; return `Long comment range ${range.start_line} - ${range.end_line}`; } } declare global { interface HTMLElementTagNameMap { 'gr-ranged-comment-hint': GrRangedCommentHint; } }
{ "content_hash": "ea26829376dfff05e28f806a6493e4e7", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 89, "avg_line_length": 26.895833333333332, "alnum_prop": 0.6382649109217661, "repo_name": "GerritCodeReview/gerrit", "id": "d7883a040fb1b984c0266d9671a93bfa2e2ec609", "size": "1378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "polygerrit-ui/app/embed/diff/gr-ranged-comment-hint/gr-ranged-comment-hint.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10735" }, { "name": "Closure Templates", "bytes": "87947" }, { "name": "Dockerfile", "bytes": "2833" }, { "name": "GAP", "bytes": "5268" }, { "name": "Go", "bytes": "2731" }, { "name": "HTML", "bytes": "65080" }, { "name": "Java", "bytes": "19516048" }, { "name": "JavaScript", "bytes": "73591" }, { "name": "Makefile", "bytes": "367" }, { "name": "Perl", "bytes": "9943" }, { "name": "Prolog", "bytes": "27464" }, { "name": "Python", "bytes": "86775" }, { "name": "Roff", "bytes": "25754" }, { "name": "Scala", "bytes": "49306" }, { "name": "Shell", "bytes": "91452" }, { "name": "Starlark", "bytes": "280825" }, { "name": "TypeScript", "bytes": "6249575" } ], "symlink_target": "" }
* blank subject line * no signature * Chinese characters * no blank line between paragraphs * unnecessary attachments * used lower case while upper case is expected * Chinese punctuations in English * no space after the punctuation * name in email account setting * auto reply * signature position - at the right hand\-side of the line - should be at the beginning of the line - this is different from letter on paper * typos - use a spell checker
{ "content_hash": "ef0f4972abcc63bf71636294df917111", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 46, "avg_line_length": 28.3125, "alnum_prop": 0.7660044150110376, "repo_name": "Lcmm/SESE", "id": "a978af5b57ff5c00733a20bf42c6516f027be098", "size": "490", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "day1/problems_in_day1_homework.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import React from 'react'; const WelcomeParallax = ({title, subTitle}) => ( <div className="container"> <h2 className="header">{title}</h2> <h5 className="header">{subTitle}</h5> </div> ); export default WelcomeParallax;
{ "content_hash": "c3ece8e7be9d64dff976b1b67793bf8d", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 48, "avg_line_length": 24.6, "alnum_prop": 0.6341463414634146, "repo_name": "easybird/easyblog", "id": "9382fed8a7c46f73c775bd9c4c997cf769ddcfcf", "size": "246", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "frontend-app/welcome-app/header/welcome-parallax.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1721" }, { "name": "JavaScript", "bytes": "64400" } ], "symlink_target": "" }
package com.programmerdan.minecraft.civspy; import java.sql.PreparedStatement; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import com.programmerdan.minecraft.civspy.database.Database; /** * Roughly similar approach to Manager; stage() unwinds data to batch it up, then * other task(s) come along to deliver to the database. * * @author ProgrammerDan * */ public class DataBatcher { private final Database db; private final Logger logger; private final AtomicLong inflowCount; private final AtomicLong outflowCount; private final AtomicInteger workerCount; private final AtomicLong periodInflowCount; private final AtomicLong periodOutflowCount; private final AtomicLong periodWorkerCount; /** * Threadpool to handle scheduled tasks, liveness tester */ private final ScheduledExecutorService scheduler; /** * Threadpool to handle batch constructors */ private final ExecutorService batchExecutor; /** * The queue for unspooled aggregations. */ private final LinkedTransferQueue<BatchLine> batchQueue; private boolean active = true; /** * Maximum number of elements to put into a single batch. */ private final long maxBatchSize; // = 100l; /** * Maximum number of milliseconds to wait on more elements to join an open batch. */ private final long maxBatchWait; // = 1000l; /** * Effectively, max simultaneous connections. A single batch is run against a single connection. */ private final int maxExecutors; // = 5; /** * Creates a new Data Batcher. * * @param db The Database to send data to. Wraps a connection pool. * @param logger The Logger instance to use for logging. * @param maxBatchSize The maximum number of elements to commit together as a batch * @param maxBatchWait The maximum amount of time to wait for that max elements to show up * @param maxBatchers The maximum number of workers constructing batches simultaneously */ public DataBatcher(final Database db, final Logger logger, final Long maxBatchSize, final Long maxBatchWait, final Integer maxBatchers) { this.db = db; this.logger = logger; this.inflowCount = new AtomicLong(0l); this.outflowCount = new AtomicLong(0l); this.workerCount = new AtomicInteger(0); this.periodInflowCount = new AtomicLong(0l); this.periodOutflowCount = new AtomicLong(0l); this.periodWorkerCount = new AtomicLong(0l); this.maxBatchSize = (maxBatchSize == null ? 100l : maxBatchSize); this.maxBatchWait = (maxBatchWait == null ? 1000l : maxBatchWait); this.maxExecutors = (maxBatchers == null ? 5 : maxBatchers); this.batchQueue = new LinkedTransferQueue<BatchLine>(); this.scheduler = Executors.newScheduledThreadPool(1); this.startWatcher(); this.batchExecutor = Executors.newFixedThreadPool(this.maxExecutors); } /** * Force an orderly shutdown of the batching process. Waits until the queue is done * or 2 minutes have elapsed. Once dequeue has occurred, waits up to 2 minutes * for the consequential commits to complete. */ public void shutdown() { active = false; int delay = 0; while (!this.batchQueue.isEmpty() && delay < 120) { if (this.workerCount.get() < this.maxExecutors) { this.generateWorker(); this.logger.log(Level.INFO, "Starting a new worker to help with offloading"); } try { Thread.sleep(1000l); } catch(Exception e) {} delay ++; if (delay % 30 == 0) { this.logger.log(Level.INFO, "Waiting on batch queue workers to finish up, {0} seconds so far", delay); } } if (delay >= 120) { this.logger.log(Level.WARNING, "Giving up on waiting. DATA LOSS MAY OCCUR."); } batchQueue.clear(); this.scheduler.shutdown(); this.batchExecutor.shutdown(); try { if (!this.batchExecutor.awaitTermination(120l, TimeUnit.SECONDS)) { this.logger.log(Level.WARNING, "Giving up on waiting for batch commit; DATA LOSS MAY HAVE OCCURRED."); } } catch (InterruptedException ie) { this.logger.log(Level.WARNING, "Was awaiting batch saving to finish, but was interrupted.", ie); } } /** * This task just keeps a worker running from time to time, just to make sure someone is watching * the incoming queue and help moderate against inflow explosion. */ private void startWatcher() { scheduler.scheduleAtFixedRate(new Runnable() { private long executions = 0; @Override public void run() { executions ++; if (workerCount.get() < 1) { generateWorker(); } if (executions % 40 == 0) { logger.log(Level.INFO, "Since last report, {0} Batch Unloaders ran. Total: {1} records received, {2} records written.", new Object[] {periodWorkerCount.getAndSet(0l), periodInflowCount.getAndSet(0l), periodOutflowCount.getAndSet(0l)}); } } }, maxBatchWait, maxBatchWait, TimeUnit.MILLISECONDS); } private void generateWorker() { try { batchExecutor.execute( new Runnable() { @Override public void run() { /* General sketch: * Based on maximum wait time and max count, pull batch lines off * and batch up into a new PrepareStatement batch against a new connection. */ PreparedStatement batch = null; long startTime = System.currentTimeMillis(); int count = 0; while (System.currentTimeMillis() - startTime < maxBatchWait && count < maxBatchSize) { try { BatchLine newLine = batchQueue.poll(maxBatchWait, TimeUnit.MILLISECONDS); if (newLine != null) { batch = db.batchData(newLine.key.getKey(), newLine.key.getServer(), newLine.key.getWorld(), newLine.key.getChunkX(), newLine.key.getChunkZ(), newLine.key.getPlayer(), newLine.valueString, newLine.valueNumber, newLine.timestamp, null, batch); count ++; outflowCount.getAndIncrement(); periodOutflowCount.getAndIncrement(); } } catch (InterruptedException ie) { logger.log(Level.WARNING, "A batching task was interrupted", ie); break; } } if (batch != null) { try { int[] results = db.batchExecute(batch, true); int inserts = 0; if (results != null) { for (int r : results) { inserts += r; } } if (inserts != results.length) { logger.log(Level.WARNING, "Some submitted data failed to insert: given {0} saved {1}", new Object[]{results.length, inserts}); } } catch (Exception e) { logger.log(Level.SEVERE, "Critical failure while saving a batch!", e); } } inflowCount.addAndGet(-count); outflowCount.addAndGet(-count); workerCount.decrementAndGet(); } }); workerCount.incrementAndGet(); periodWorkerCount.incrementAndGet(); } catch (RejectedExecutionException ree) { logger.log(Level.WARNING, "Tried to scheduled a new batch worker, rejected: ", ree); } } /** * {@link DataManager} calls this to queue aggregates up for batch commit. * * @param key The {@link DataSampleKey} to index this aggregate against. * @param aggregate A {@link DataAggregate} which holds either one or more aggregations of data over a time period. */ public void stage(DataSampleKey key, DataAggregate aggregate) { if (!active) return; // now unwrap if (aggregate.sum != null) { this.batchQueue.offer(new BatchLine(key, aggregate.getTimestamp(), null, aggregate.sum)); this.inflowCount.getAndIncrement(); this.periodInflowCount.getAndIncrement(); } for (Entry<String, Double> entry : aggregate.namedSums.entrySet()) { this.batchQueue.offer(new BatchLine(key, aggregate.getTimestamp(), entry.getKey(), entry.getValue())); this.inflowCount.getAndIncrement(); this.periodInflowCount.getAndIncrement(); } if (this.inflowCount.get() - this.outflowCount.get() >= maxBatchSize) { if (this.workerCount.get() < this.maxExecutors) { this.generateWorker(); } else { //logger.log(Level.WARNING, "Inflow count far in advance of outflow count, but no room for more outflow workers. Check your config!"); } } } /** * Lightweight unwrap for aggregator */ static class BatchLine { DataSampleKey key; long timestamp; String valueString; Double valueNumber; public BatchLine(DataSampleKey key, long timestamp, String valueString, Double valueNumber) { this.key = key; this.timestamp = timestamp; this.valueString = valueString; this.valueNumber = valueNumber; } } }
{ "content_hash": "bc9e5f05341480e2461af4fc2fc54bd4", "timestamp": "", "source": "github", "line_count": 271, "max_line_length": 138, "avg_line_length": 32.981549815498155, "alnum_prop": 0.6924367867531886, "repo_name": "ProgrammerDan/CivSpy", "id": "bd9dca62ba283f9973f71176b14e18828633eac4", "size": "8938", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CivSpy-Bukkit/src/main/java/com/programmerdan/minecraft/civspy/DataBatcher.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "38526" }, { "name": "HTML", "bytes": "1371064" }, { "name": "Java", "bytes": "160260" }, { "name": "JavaScript", "bytes": "2481" } ], "symlink_target": "" }
package com.microsoft.azure.management.recoveryservices.backup.v2016_06_01.implementation; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.CloudException; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import java.io.IOException; import okhttp3.ResponseBody; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in JobOperationResults. */ public class JobOperationResultsInner { /** The Retrofit service to perform REST calls. */ private JobOperationResultsService service; /** The service client containing this operation class. */ private RecoveryServicesBackupClientImpl client; /** * Initializes an instance of JobOperationResultsInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public JobOperationResultsInner(Retrofit retrofit, RecoveryServicesBackupClientImpl client) { this.service = retrofit.create(JobOperationResultsService.class); this.client = client; } /** * The interface defining all the services for JobOperationResults to be * used by Retrofit to perform actually REST calls. */ interface JobOperationResultsService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.backup.v2016_06_01.JobOperationResults get" }) @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs/{jobName}/operationResults/{operationId}") Observable<Response<ResponseBody>> get(@Path("vaultName") String vaultName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("jobName") String jobName, @Path("operationId") String operationId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Gets the result of the operation. * * @param vaultName The name of the Recovery Services vault. * @param resourceGroupName The name of the resource group associated with the Recovery Services vault. * @param jobName Job name associated with this GET operation. * @param operationId OperationID associated with this GET operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void get(String vaultName, String resourceGroupName, String jobName, String operationId) { getWithServiceResponseAsync(vaultName, resourceGroupName, jobName, operationId).toBlocking().single().body(); } /** * Gets the result of the operation. * * @param vaultName The name of the Recovery Services vault. * @param resourceGroupName The name of the resource group associated with the Recovery Services vault. * @param jobName Job name associated with this GET operation. * @param operationId OperationID associated with this GET operation. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> getAsync(String vaultName, String resourceGroupName, String jobName, String operationId, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(vaultName, resourceGroupName, jobName, operationId), serviceCallback); } /** * Gets the result of the operation. * * @param vaultName The name of the Recovery Services vault. * @param resourceGroupName The name of the resource group associated with the Recovery Services vault. * @param jobName Job name associated with this GET operation. * @param operationId OperationID associated with this GET operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> getAsync(String vaultName, String resourceGroupName, String jobName, String operationId) { return getWithServiceResponseAsync(vaultName, resourceGroupName, jobName, operationId).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Gets the result of the operation. * * @param vaultName The name of the Recovery Services vault. * @param resourceGroupName The name of the resource group associated with the Recovery Services vault. * @param jobName Job name associated with this GET operation. * @param operationId OperationID associated with this GET operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> getWithServiceResponseAsync(String vaultName, String resourceGroupName, String jobName, String operationId) { if (vaultName == null) { throw new IllegalArgumentException("Parameter vaultName is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (jobName == null) { throw new IllegalArgumentException("Parameter jobName is required and cannot be null."); } if (operationId == null) { throw new IllegalArgumentException("Parameter operationId is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.get(vaultName, resourceGroupName, this.client.subscriptionId(), jobName, operationId, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = getDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .register(202, new TypeToken<Void>() { }.getType()) .register(204, new TypeToken<Void>() { }.getType()) .registerError(CloudException.class) .build(response); } }
{ "content_hash": "18d7d9338625195b9eb7362784a2d8cb", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 389, "avg_line_length": 52.174193548387095, "alnum_prop": 0.7091628539631507, "repo_name": "selvasingh/azure-sdk-for-java", "id": "a7460e4c52d7fe9e58d6448a8c542575e649ddf6", "size": "8317", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sdk/recoveryservices.backup/mgmt-v2016_06_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_06_01/implementation/JobOperationResultsInner.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "29891970" }, { "name": "JavaScript", "bytes": "6198" }, { "name": "PowerShell", "bytes": "160" }, { "name": "Shell", "bytes": "609" } ], "symlink_target": "" }
<div class="btn-group"> <button class="btn btn-default pager-btn {% if not page_obj.has_previous %}disabled"{% else %}" data-page="{{ page_obj.previous_page_number }}"{% endif %} aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </button> {% for page_num in page_obj.paginator.page_range %} <a href="?page={{ page_num }}" class="btn btn-default pager-btn {% if page_num == page_obj.number %}active{% endif %}"> {{ page_num }} </a> {% endfor %} <button class="btn btn-default pager-btn {% if not page_obj.has_next %}disabled"{% else %}" data-page="{{ page_obj.next_page_number }}"{% endif %} aria-label="Previous"> <span aria-hidden="true">&raquo;</span> </button> </div>
{ "content_hash": "2f99358a1ee93a551286bdbdd75c22c9", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 181, "avg_line_length": 49.4, "alnum_prop": 0.6032388663967612, "repo_name": "PeteAndersen/swarfarm", "id": "09a5d98bd088df4abd02c5973cf5a2516adce2da", "size": "741", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "herders/templates/herders/profile/data_logs/pagination.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "31891" }, { "name": "HTML", "bytes": "352588" }, { "name": "JavaScript", "bytes": "79075" }, { "name": "Python", "bytes": "982216" }, { "name": "Shell", "bytes": "3403" } ], "symlink_target": "" }
<?php namespace SclZfCart\CartItem; use SCL\Currency\TaxedPrice; interface UnitPriceProviderInterface { /** * @return TaxedPrice */ public function getUnitPrice(); }
{ "content_hash": "c7c48a15b428d8ac68c6e90eddab9637", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 36, "avg_line_length": 14.384615384615385, "alnum_prop": 0.6951871657754011, "repo_name": "SCLInternet/SclZfCart", "id": "2c6c3a93de4116c239df4976c0ec002777a14b89", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SclZfCart/CartItem/UnitPriceProviderInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1509" }, { "name": "PHP", "bytes": "132349" } ], "symlink_target": "" }
using System; using System.Web.Http.Filters; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web.Composing; namespace Umbraco.Web.WebApi.Filters { /// <summary> /// Appends a custom response header to notify the UI that the current user data has been modified /// </summary> public sealed class AppendUserModifiedHeaderAttribute : ActionFilterAttribute { private readonly string _userIdParameter; /// <summary> /// An empty constructor which will always set the header /// </summary> public AppendUserModifiedHeaderAttribute() { } /// <summary> /// A constructor specifying the action parameter name containing the user id to match against the current user and if they match the header will be appended /// </summary> /// <param name="userIdParameter"></param> public AppendUserModifiedHeaderAttribute(string userIdParameter) { if (userIdParameter == null) throw new ArgumentNullException("userIdParameter"); _userIdParameter = userIdParameter; } public static void AppendHeader(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Response.Headers.Contains("X-Umb-User-Modified") == false) { actionExecutedContext.Response.Headers.Add("X-Umb-User-Modified", "1"); } } public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { base.OnActionExecuted(actionExecutedContext); if (_userIdParameter.IsNullOrWhiteSpace()) { AppendHeader(actionExecutedContext); } else { var actionContext = actionExecutedContext.ActionContext; if (actionContext.ActionArguments[_userIdParameter] == null) { throw new InvalidOperationException("No argument found for the current action with the name: " + _userIdParameter); } var user = Current.UmbracoContext.Security.CurrentUser; if (user == null) return; var userId = GetUserIdFromParameter(actionContext.ActionArguments[_userIdParameter]); if (userId == user.Id) AppendHeader(actionExecutedContext); } } private int GetUserIdFromParameter(object parameterValue) { if (parameterValue is int) { return (int)parameterValue; } throw new InvalidOperationException("The id type: " + parameterValue.GetType() + " is not a supported id"); } } }
{ "content_hash": "deca533d438beb6f05c9481d8d00bbb9", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 165, "avg_line_length": 35.883116883116884, "alnum_prop": 0.6134636264929425, "repo_name": "leekelleher/Umbraco-CMS", "id": "5ac8d886f068745160753dc0d727d80b3abddc01", "size": "2765", "binary": false, "copies": "8", "ref": "refs/heads/v8/contrib", "path": "src/Umbraco.Web/WebApi/Filters/AppendUserModifiedHeaderAttribute.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "484235" }, { "name": "Batchfile", "bytes": "16156" }, { "name": "C#", "bytes": "16505882" }, { "name": "CSS", "bytes": "676666" }, { "name": "HTML", "bytes": "776273" }, { "name": "JavaScript", "bytes": "4045587" }, { "name": "PowerShell", "bytes": "18034" }, { "name": "Python", "bytes": "876" }, { "name": "Ruby", "bytes": "765" }, { "name": "XSLT", "bytes": "50045" } ], "symlink_target": "" }
@extends('core::app.layout') @section('content') <div id="page-content"> <ul class="breadcrumb breadcrumb-top"> @include('point-sales::app.sales.point.sales._breadcrumb') <li><a href="{{ url('sales/point/indirect/delivery-order') }}">Delivery Order</a></li> <li>Show</li> </ul> <h2 class="sub-header">Delivery Order</h2> @include('point-sales::app.sales.point.sales.delivery-order._menu') @include('core::app.error._alert') <div class="block full"> <!-- Block Tabs Title --> <div class="block-title"> <ul class="nav nav-tabs" data-toggle="tabs"> <li class="active"><a href="#block-tabs-home">Form</a></li> <li><a href="#block-tabs-settings"><i class="gi gi-settings"></i></a></li> </ul> </div> <!-- END Block Tabs Title --> <!-- Tabs Content --> <div class="tab-content"> <div class="tab-pane active" id="block-tabs-home"> <div class="form-horizontal form-bordered"> <fieldset> <div class="form-group pull-right"> <div class="col-md-12"> @include('framework::app.include._approval_status_label', [ 'approval_status' => $delivery_order->formulir->approval_status, 'approval_message' => $delivery_order->formulir->approval_message, 'approval_at' => $delivery_order->formulir->approval_at, 'approval_to' => $delivery_order->formulir->approvalTo->name, ]) @include('framework::app.include._form_status_label', ['form_status' => $delivery_order->formulir->form_status]) </div> </div> </fieldset> <fieldset> <div class="form-group"> <div class="col-md-12"> <legend><i class="fa fa-angle-right"></i> Info Reference</legend> </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Form Date</label> <div class="col-md-6 content-show"> {{ date_format_view($reference->formulir->form_date, true) }} </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Form Number</label> <div class="col-md-6 content-show"> <a target="_blank" href="{{url('sales/point/indirect/sales-order/'.$reference->id)}}"> {{ $reference->formulir->form_number }} </a> </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Customer</label> <div class="col-md-6 content-show"> {!! get_url_person($reference->person->id) !!} </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Remaining Downpayment</label> <div class="col-md-6 content-show"> <?php $remaining_downpayment = $reference->getTotalRemainingDownpayment($reference->id);?> {{ number_format_price($remaining_downpayment) }} </div> </div> </fieldset> <fieldset> <div class="form-group"> <div class="col-md-12"> <legend><i class="fa fa-angle-right"></i> Delivery Order Form</legend> </div> </div> </fieldset> @if($revision) <div class="form-group"> <label class="col-md-3 control-label">Revision</label> <div class="col-md-6 content-show"> {{ $revision }} </div> </div> @endif <div class="form-group"> <label class="col-md-3 control-label">Form Number</label> <div class="col-md-6 content-show"> {{ $delivery_order->formulir->form_number }} </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Form Date</label> <div class="col-md-6 content-show"> {{ date_format_view($delivery_order->formulir->form_date, true) }} </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Warehouse</label> <div class="col-md-6 content-show"> {{ $delivery_order->warehouse->codeName }} </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Driver</label> <div class="col-md-6 content-show"> {{ $delivery_order->driver }} </div> </div> <div class="form-group"> <label class="col-md-3 control-label">License Plate</label> <div class="col-md-6 content-show"> {{ $delivery_order->license_plate }} </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Notes</label> <div class="col-md-6 content-show"> {{ $delivery_order->formulir->notes }} </div> </div> <fieldset> <div class="form-group"> <div class="col-md-12"> <legend><i class="fa fa-angle-right"></i> Item</legend> </div> </div> <div class="form-group"> <div class="col-md-12"> <div class="table-responsive"> <table id="item-datatable" class="table table-striped"> <thead> <tr> <th>ITEM</th> <th class="text-right">QUANTITY</th> <th>UNIT</th> </tr> </thead> <tbody class="manipulate-row"> @foreach($delivery_order->items as $delivery_order_item) <tr> <td>{{ $delivery_order_item->item->codeName }}</td> <td class="text-right">{{ number_format_quantity($delivery_order_item->quantity) }}</td> <td>{{ $delivery_order_item->unit }}</td> </tr> @endforeach </tbody> </table> </div> </div> </div> </fieldset> <fieldset> <div class="form-group"> <div class="col-md-12"> <legend><i class="fa fa-angle-right"></i> Authorized User</legend> </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Form Creator</label> <div class="col-md-6 content-show"> {{ $delivery_order->formulir->createdBy->name }} </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Request Approval To</label> <div class="col-md-6 content-show"> {{ $delivery_order->formulir->approvalTo->name }} </div> </div> </fieldset> </div> </div> <div class="tab-pane" id="block-tabs-settings"> <fieldset> <div class="form-group"> <div class="col-md-12"> <legend><i class="fa fa-angle-right"></i> Action</legend> </div> </div> <div class="form-group"> <div class="col-md-12"> @if(formulir_view_edit($delivery_order->formulir, 'update.point.sales.delivery.order')) <a href="{{url('sales/point/indirect/delivery-order/'.$delivery_order->id.'/edit')}}" class="btn btn-effect-ripple btn-info"><i class="fa fa-pencil"></i> Edit</a> @endif @if(formulir_view_cancel($delivery_order->formulir, 'delete.point.sales.delivery.order')) <a href="javascript:void(0)" class="btn btn-effect-ripple btn-danger" onclick="secureCancelForm('{{url('formulir/cancel')}}', '{{ $delivery_order->formulir_id }}', 'delete.point.sales.delivery.order')"><i class="fa fa-times"></i> Cancel Form</a> @endif @if(formulir_view_close($delivery_order->formulir, 'update.point.sales.delivery.order')) <a href="javascript:void(0)" class="btn btn-effect-ripple btn-danger" onclick="secureCloseForm({{$delivery_order->formulir_id}},'{{url('formulir/close')}}')">Close Form</a> @endif @if(formulir_view_reopen($delivery_order->formulir, 'update.point.sales.delivery.order')) <a href="javascript:void(0)" class="btn btn-effect-ripple btn-danger" onclick="secureReopenForm({{$delivery_order->formulir_id}},'{{url('formulir/reopen')}}')">Reopen Form</a> @endif @if(formulir_view_email_vendor($delivery_order->formulir, 'create.point.sales.invoice')) <a class="btn btn-effect-ripple btn-info" href="{{url('sales/point/indirect/delivery-order/'.$delivery_order->id.'/export')}}">Print</a> @endif </div> </div> </fieldset> @if(formulir_view_approval($delivery_order->formulir, 'approval.point.sales.delivery.order')) <fieldset> <div class="form-group"> <div class="col-md-12"> <legend><i class="fa fa-angle-right"></i> Approval Action</legend> </div> </div> <div class="form-group"> <div class="col-md-6"> <form action="{{url('sales/point/indirect/delivery-order/'.$delivery_order->id.'/approve')}}" method="post"> {!! csrf_field() !!} <div class="input-group"> <input type="text" name="approval_message" class="form-control" placeholder="Message"> <span class="input-group-btn"> <input type="submit" class="btn btn-primary" value="Approve"> </span> </div> </form> </div> <div class="col-md-6"> <form action="{{url('sales/point/indirect/delivery-order/'.$delivery_order->id.'/reject')}}" method="post"> {!! csrf_field() !!} <div class="input-group"> <input type="text" name="approval_message" class="form-control" placeholder="Message"> <span class="input-group-btn"> <input type="submit" class="btn btn-danger" value="Reject"> </span> </div> </form> </div> </div> </fieldset> @endif @if($list_delivery_order_archived->count() > 0) <fieldset> <div class="form-group"> <div class="col-md-12"> <legend><i class="fa fa-angle-right"></i> Archived Form</legend> </div> </div> <div class="form-group"> <div class="col-md-12 content-show"> <div class="table-responsive"> <table class="table table-striped table-bordered"> <thead> <tr> <th></th> <th>Form Date</th> <th>Form Number</th> <th>Created By</th> <th>Updated By</th> </tr> </thead> <tbody> <?php $count = 0;?> @foreach($list_delivery_order_archived as $delivery_order_archived) <tr> <td class="text-center"> <a href="{{ url('sales/point/indirect/delivery-order/'.$delivery_order_archived->formulirable_id.'/archived') }}" data-toggle="tooltip" title="Show" class="btn btn-effect-ripple btn-xs btn-info"><i class="fa fa-file"></i> {{ 'Revision ' . $count++ }} </a> </td> <td>{{ date_format_view($delivery_order->formulir->form_date) }}</td> <td>{{ $delivery_order_archived->formulir->archived }}</td> <td>{{ $delivery_order_archived->formulir->createdBy->name }}</td> <td>{{ $delivery_order_archived->formulir->updatedBy->name }}</td> </tr> @endforeach </tbody> </table> </div> </div> </div> </fieldset> @endif </div> </div> <!-- END Tabs Content --> </div> </div> @stop @section('scripts') <script> initDatatable('#item-datatable'); </script> @stop
{ "content_hash": "1f30fdbeeafefeffb1cb36a0667cd3a3", "timestamp": "", "source": "github", "line_count": 326, "max_line_length": 169, "avg_line_length": 57.015337423312886, "alnum_prop": 0.334427287889385, "repo_name": "pringgojs/point-app-test", "id": "ca279546e0101667b2cb33bae893bb79e1fbd0f1", "size": "18587", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/point/point-sales/src/views/app/sales/point/sales/delivery-order/show.blade.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "CSS", "bytes": "917733" }, { "name": "HTML", "bytes": "6373428" }, { "name": "JavaScript", "bytes": "787585" }, { "name": "PHP", "bytes": "3421396" } ], "symlink_target": "" }
""" # Licensed to the Apache Software Foundation (ASF) under one * # or more contributor license agreements. See the NOTICE file * # distributed with this work for additional information * # regarding copyright ownership. The ASF licenses this file * # to you under the Apache License, Version 2.0 (the * # "License"); you may not use this file except in compliance * # with the License. You may obtain a copy of the License at * # * # http://www.apache.org/licenses/LICENSE-2.0 * # * # Unless required by applicable law or agreed to in writing, * # software distributed under the License is distributed on an * # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * # KIND, either express or implied. See the License for the * # specific language governing permissions and limitations * # under the License. """ from __future__ import absolute_import from . import msg #from . import support #from . import transport #from . import util
{ "content_hash": "ce4b8b95b3e1119bef07554fbab493df", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 65, "avg_line_length": 47.791666666666664, "alnum_prop": 0.6102877070619006, "repo_name": "OBIGOGIT/etch", "id": "73e3a00315767d38caf9ef20b2252fdf34fe8bba", "size": "1147", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "binding-python/runtime/src/main/python/etch/binding/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2513090" }, { "name": "C#", "bytes": "1514713" }, { "name": "C++", "bytes": "1109601" }, { "name": "CSS", "bytes": "143" }, { "name": "Go", "bytes": "158833" }, { "name": "Java", "bytes": "2451144" }, { "name": "Perl", "bytes": "290" }, { "name": "Python", "bytes": "444086" }, { "name": "Shell", "bytes": "62900" }, { "name": "VimL", "bytes": "13679" }, { "name": "XSLT", "bytes": "12890" } ], "symlink_target": "" }
package io.clickhandler.materialUiGwt.client; import io.clickhandler.reactGwt.client.dom.StyleProps; import io.clickhandler.reactGwt.client.react.BaseProps; import io.clickhandler.reactGwt.client.react.ExternalComponent; import io.clickhandler.reactGwt.client.react.ReactClass; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import javax.inject.Inject; import javax.inject.Singleton; /** * Card_u consists of many different parts that share property names: * for now they are separate classes * 1. Card_u * 2. CardActions * 3. CardHeader * 4. CardMedia * 5. CardTitle * 6. CardText */ @Singleton public class CardText extends ExternalComponent<CardText.Props> { @Inject public CardText() { } @Override protected native ReactClass<Props> getReactClass() /*-{ return $wnd.MaterialUi.CardText; }-*/; @JsType(isNative = true) public interface Props extends BaseProps { @JsProperty boolean isActAsExpander(); @JsProperty void setActAsExpander(boolean actAsExpander); @JsProperty boolean isExpandable(); @JsProperty void setExpandable(boolean expandable); @JsProperty String getColor(); @JsProperty void setColor(String color); @JsProperty StyleProps getStyle(); @JsProperty void setStyle(StyleProps style); //////////////////// // fluent setters //////////////////// @JsOverlay default Props actAsExpander(final boolean actAsExpander) { setActAsExpander(actAsExpander); return this; } @JsOverlay default Props expandable(final boolean expandable) { setExpandable(expandable); return this; } @JsOverlay default Props color(final String color) { setColor(color); return this; } @JsOverlay default Props style(final StyleProps style) { setStyle(style); return this; } } }
{ "content_hash": "53f9166823a20b82d87834f3da8b679e", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 69, "avg_line_length": 23.150537634408604, "alnum_prop": 0.6307477937761263, "repo_name": "ClickHandlerIO/material-ui-gwt", "id": "865febab9c5c73df796fac74d978ffba9a0ce869", "size": "2153", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/io/clickhandler/materialUiGwt/client/CardText.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "56146" }, { "name": "Java", "bytes": "292804" }, { "name": "JavaScript", "bytes": "188116" }, { "name": "Shell", "bytes": "531" } ], "symlink_target": "" }
var searchData= [ ['circlebody',['CircleBody',['../class_circle_body.html',1,'']]], ['collisionhandler',['CollisionHandler',['../struct_world_1_1_collision_handler.html',1,'World']]], ['constraint',['Constraint',['../class_constraint.html',1,'']]] ];
{ "content_hash": "e9b63e64d2c74d3a74d62d5d0e96ed5c", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 101, "avg_line_length": 42.833333333333336, "alnum_prop": 0.6381322957198443, "repo_name": "aderussell/ARPhysics", "id": "659f339ef9d9a61bf73aac535412f72a87143bd1", "size": "257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Documentation/html/search/classes_63.js", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "1132" }, { "name": "C++", "bytes": "498860" } ], "symlink_target": "" }
package org.lognavigator.service; import static org.junit.Assert.*; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.junit.Test; import org.lognavigator.bean.LogAccessConfig; import org.lognavigator.bean.LogAccessConfig.LogAccessType; import org.lognavigator.exception.AuthorizationException; import org.lognavigator.service.AuthorizationService; import org.lognavigator.service.DefaultAuthorizationService; import org.springframework.security.authentication.TestingAuthenticationToken; public class DefaultAuthorizationServiceTest { private AuthorizationService authorizationService = new DefaultAuthorizationService(); @Test public void testCheckUserAuthorizationFor_Authorized() throws Exception { // given LogAccessConfig logAccessConfig = new LogAccessConfig("log-with-onerole-authorized", LogAccessType.LOCAL, "localhost", "/log"); logAccessConfig.setAuthorizedRoles(Arrays.asList("onerole")); TestingAuthenticationToken authenticatedUser = new TestingAuthenticationToken("anyuser", null, "onerole"); // when authorizationService.checkUserAuthorizationFor(logAccessConfig, authenticatedUser); // then // No AuthorizationException } @Test(expected=AuthorizationException.class) public void testCheckUserAuthorizationFor_NotAuthorized() throws Exception { // given LogAccessConfig logAccessConfig = new LogAccessConfig("log-with-onerole-authorized", LogAccessType.LOCAL, "localhost", "/log"); logAccessConfig.setAuthorizedRoles(Arrays.asList("onerole")); TestingAuthenticationToken authenticatedUser = new TestingAuthenticationToken("anyuser", null, "not-authorized-role"); // when authorizationService.checkUserAuthorizationFor(logAccessConfig, authenticatedUser); // then // raise AuthorizationException } @Test public void testGetAuthorizedLogAccessConfigs() throws Exception { // given Set<LogAccessConfig> allLogAccessConfigs = new HashSet<LogAccessConfig>(); LogAccessConfig logAccessConfig = new LogAccessConfig("log-with-onerole-authorized", LogAccessType.LOCAL, "localhost", "/log"); logAccessConfig.setAuthorizedRoles(Arrays.asList("onerole")); allLogAccessConfigs.add(logAccessConfig); logAccessConfig = new LogAccessConfig("log-with-oneuser-authorized", LogAccessType.LOCAL, "localhost", "/log"); logAccessConfig.setAuthorizedUsers(Arrays.asList("oneuser")); allLogAccessConfigs.add(logAccessConfig); TestingAuthenticationToken authenticatedUser = new TestingAuthenticationToken("anyuser", null, "onerole"); // when Set<LogAccessConfig> authorizedLogAccessConfigs = authorizationService.getAuthorizedLogAccessConfigs(allLogAccessConfigs, authenticatedUser); // then assertEquals(1, authorizedLogAccessConfigs.size()); assertEquals("log-with-onerole-authorized", authorizedLogAccessConfigs.iterator().next().getId()); } }
{ "content_hash": "977c2f0926c132a2bdab7aaa0842970a", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 143, "avg_line_length": 38.932432432432435, "alnum_prop": 0.804581742450538, "repo_name": "fbaligand/lognavigator", "id": "f721dd8e935399c730749197d3d2970c4ed31fb3", "size": "2881", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/lognavigator/service/DefaultAuthorizationServiceTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2571" }, { "name": "Java", "bytes": "175325" }, { "name": "JavaScript", "bytes": "7193" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="192dp" android:background="?attr/colorPrimaryDark" android:padding="16dp" android:theme="@style/ThemeOverlay.AppCompat.Dark" android:orientation="vertical" android:gravity="bottom" android:weightSum="1"> <ImageView android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/logo_outline_white" android:layout_alignParentBottom="true" android:layout_alignParentStart="true" android:id="@+id/imageView2" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="40dp" android:text="SnapSplit" android:textAppearance="@style/TextAppearance.AppCompat.Body1" android:textColor="@android:color/white" android:textSize="24dp" android:layout_alignParentBottom="true" android:layout_toEndOf="@+id/imageView2" /> </RelativeLayout>
{ "content_hash": "08764bf074f84d763a12c93f4a867900", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 70, "avg_line_length": 35.0625, "alnum_prop": 0.6755793226381461, "repo_name": "menghou0924/snapsplit", "id": "7343d74f66fce17d004b9f80e35b4de615af5c70", "size": "1122", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/nav_header.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "372786" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2016 Red Hat, Inc. and/or its affiliates ~ and other contributors as indicated by the @author tags. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>keycloak-parent</artifactId> <groupId>org.keycloak</groupId> <version>2.5.0.Final-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <packaging>pom</packaging> <artifactId>keycloak-federation-parent</artifactId> <name>Keycloak Federation</name> <description /> <modules> <module>kerberos</module> <module>ldap</module> <module>sssd</module> </modules> </project>
{ "content_hash": "c54d455dce8284cf8521639b0342894d", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 108, "avg_line_length": 36.292682926829265, "alnum_prop": 0.6780913978494624, "repo_name": "manuel-palacio/keycloak", "id": "b7766646fd3bfd480ba0c093ee091c323557242f", "size": "1488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "federation/pom.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "4656" }, { "name": "Batchfile", "bytes": "4699" }, { "name": "CSS", "bytes": "347550" }, { "name": "FreeMarker", "bytes": "84188" }, { "name": "HTML", "bytes": "672245" }, { "name": "Java", "bytes": "15793166" }, { "name": "JavaScript", "bytes": "714334" }, { "name": "Shell", "bytes": "8437" }, { "name": "XSLT", "bytes": "69562" } ], "symlink_target": "" }
class PagesController < ApplicationController skip_before_filter :require_login, :only => [:imprint] add_breadcrumb I18n.t("pages.imprint.title"), "/pages/imprint" end
{ "content_hash": "a7e91bdf97299adb20890e28e3777bbd", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 64, "avg_line_length": 35, "alnum_prop": 0.7428571428571429, "repo_name": "afritsch/fhs-meet-ideas", "id": "b6783033cfdf0b1e6e16ab9d20aaa1430c11fc66", "size": "175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/pages_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1685" }, { "name": "Ruby", "bytes": "62864" } ], "symlink_target": "" }
<!-- DO NOT EDIT. This file has been generated. Source: ./tools/build-compute-kind-widget-fallback-props.py --> <!DOCTYPE html> <meta charset="utf-8"> <title>CSS Basic User Interface Test: Compute kind of widget: border-inline-end-style disables native appearance for progress</title> <link rel="help" href="https://drafts.csswg.org/css-ui-4/#computing-kind-widget"> <meta name="assert" content="appropriate widget is returned when authorProps includes border-inline-end-style."> <link rel="match" href="../compute-kind-widget-fallback-progress-ref.html"> <style> #container { width: 500px; } #container > #search-text-input { appearance: textfield; } #container > #select-menulist-button { appearance: none; appearance: menulist-button; } </style> <div id="container"> <progress id="progress" value=0.5></progress> </div> <script> // Set author-level CSS that matches UA style, but don't use the 'revert' value. const elements = document.querySelectorAll('#container > *'); const prop = "border-inline-end-style"; for (const el of elements) { el.style.setProperty(prop, getComputedStyle(el).getPropertyValue(prop)); } </script>
{ "content_hash": "e12a5df712fe6969480f7fc8da5d02be", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 133, "avg_line_length": 42.7037037037037, "alnum_prop": 0.7259323503902863, "repo_name": "nwjs/chromium.src", "id": "e16bb5a9488717e95466dbb9d935dcd9e7e63b9c", "size": "1153", "binary": false, "copies": "15", "ref": "refs/heads/nw70", "path": "third_party/blink/web_tests/external/wpt/css/css-ui/compute-kind-widget-generated/kind-of-widget-fallback-progress-border-inline-end-style-001.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
This is a small program dedicated to reducing the number of colors in an image. It operates with files in PNG or binary PPM format ([Portable PixMap][ppm]), and features automatic palette generation (using a median-cut algorithm) and dithering implemented with the Floyd-Steinberg method. ## Installing #### On macOS with [Homebrew][brw] $ brew install tessarin/core/dither #### Manual Installation First, install [`libpng`][lpg]. Running `make` will then compile the program and generate the documentation (requires Perl). To install, move the executable and manual files to appropriate directories in your system. $ make $ mv dither ~/bin $ mv dither.1 ~/man/man1 Individual targets can also be specified to only compile the program or to generate the manual page: $ make dither $ make doc ## Usage $ dither [-p name.size] [-dv] input output Detailed information about the program options are included in the [manual][man]. ## Features By default, `dither` will use a 3-bit RGB palette and dithering when processing an image. Other possible palettes include: - Grayscale of any given size - Automatic, generated with the given size using a median-cut quantization algorithm - Custom palette Dithering on the final image can be disabled and the program can also be used just to generate a palette. ## Samples #### Automatic Palette $ dither -p auto.32 bird-original.png bird-auto.32.png ![original bird](samples/bird-original.png) ![generated bird](samples/bird-auto.32.png) #### 1-bit Black & White $ dither -p bw flower-original.png flower-bw.png ![original flower](samples/flower-original.png) ![generated flower](samples/flower-bw.png) #### 50% Gray Test Generates a perfect checkerboard pattern. $ dither -p bw gray-original.png gray-dithered.png ![original gray](samples/gray-original.png) ![dithered gray](samples/gray-dithered.png) [ppm]: https://en.wikipedia.org/wiki/Netpbm_format [brw]: https://brew.sh [lpg]: http://www.libpng.org/pub/png/libpng.html [man]: dither.pod
{ "content_hash": "4a4089106b9c1821d9d4fa10e954a6a6", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 77, "avg_line_length": 27.092105263157894, "alnum_prop": 0.7362797474502185, "repo_name": "tessarin/dither", "id": "38466b78a9c7d0f91ae5845ea2858553ec081d99", "size": "2104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "19120" }, { "name": "Makefile", "bytes": "593" } ], "symlink_target": "" }
/* * insertionIndex(), index(), trimToSize() are based on code provided by fastutil They are based * from add(), contains() and other methods from ObjectOpenHashSet We have used the traversing * mechanism and the HashCommon.mix() */ package org.apache.geode.cache.query.internal.index; import static it.unimi.dsi.fastutil.HashCommon.arraySize; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import it.unimi.dsi.fastutil.HashCommon; import org.apache.geode.annotations.internal.MutableForTesting; import org.apache.geode.cache.query.TypeMismatchException; import org.apache.geode.cache.query.internal.parse.OQLLexerTokenTypes; import org.apache.geode.cache.query.internal.types.TypeUtils; import org.apache.geode.internal.cache.CachePerfStats; import org.apache.geode.pdx.internal.PdxString; /** * An implementation of the <tt>Set</tt> interface for the HashIndex Not exactly a set as the hash * keys can actually collide but will continue to look for an empty location to store the value * */ public class HashIndexSet implements Set { /** * optional statistics object to track number of hash collisions and time spent probing based on * hash collisions */ class HashIndexSetProperties { /** the set of Objects */ protected final transient Object[] set; /** used for hashing into the table **/ protected final int mask; /** the current number of entries in the set */ protected transient int size = 0; /** * the current number of open slots in the hash. Originally used when we collapsed collided keys * into collections Not really used now */ protected transient int free; /** number of removed tokens in the set, these are index positions that may be reused */ transient int removedTokens; /** size of the backing table (-1) **/ protected int n; /** * The maximum number of elements before rehashing */ protected int maxSize; private int computeNumFree() { return n - size; } public HashIndexSetProperties(final Object[] set, final int mask) { this.set = set; this.mask = mask; } } private transient CachePerfStats cacheStats; /** the load above which rehashing occurs. */ protected static final float DEFAULT_LOAD_FACTOR = 0.5f; protected static final int DEFAULT_INITIAL_CAPACITY = 128; protected float _loadFactor; /** * If after an update, the number of removed tokens X percent of the max size, we will compact and * rehash to remove the tokens. */ protected static final float CONDITIONAL_REMOVED_TOKEN_REHASH_FACTOR = .7f; HashIndexSetProperties hashIndexSetProperties; protected HashIndex.IMQEvaluator _imqEvaluator; /** * The removed token */ protected static final Object REMOVED = new Object(); @MutableForTesting static boolean TEST_ALWAYS_REHASH = false; /** * This is used when inplace modification is off to detect old key */ public HashIndexSet() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } /** * Creates a new <code>HashIndexSet</code> instance with a prime capacity equal to or greater than * <tt>initialCapacity</tt> and with the specified load factor. * * @param initialCapacity an <code>int</code> value * @param loadFactor a <code>float</code> value */ private HashIndexSet(int initialCapacity, float loadFactor) { setUp(initialCapacity, loadFactor); } public void setEvaluator(HashIndex.IMQEvaluator evaluator) { _imqEvaluator = evaluator; } /** * Set the statistics object for tracking hash code collisions. Should be called before the first * element is added. */ public void setCachePerfStats(CachePerfStats stats) { cacheStats = stats; } /** * Searches the set for <tt>obj</tt> * * @param obj an <code>Object</code> value * @return a <code>boolean</code> value */ @Override public boolean contains(Object obj) { return index(obj) >= 0; } /** * @param object is the index key * @return the hash key */ private int computeHash(Object object) { return object.hashCode(); } /** * Locates the index of <tt>obj</tt>. * * @param obj an <code>Object</code> value, expected to be the value object * @return the index of <tt>obj</tt> or -1 if it isn't in the set. */ protected int index(Object obj) { return index(_imqEvaluator.evaluateKey(obj), obj); } protected int index(Object key, Object obj) { return index(key, obj, -1); } /** * Locates index slot of object using the provided key (in this case we are passing in old key) * * @return the indexSlot of the given key/object combination */ protected int index(Object key, Object obj, int ignoreThisSlot) { HashIndexSetProperties metaData = hashIndexSetProperties; int hash; int pos; Object[] set = metaData.set; int mask = metaData.mask; Object curr; hash = computeHash(key); /* * Code originated from fastutils Copyright (C) 2002-2014 Sebastiano Vigna * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ if (!((curr = set[pos = (it.unimi.dsi.fastutil.HashCommon.mix(hash)) & mask]) == null || curr == REMOVED)) { if (((curr).equals(obj) && pos != ignoreThisSlot)) { return pos; } while (!((curr = set[pos = (pos + 1) & mask]) == null || curr == REMOVED)) { if (((curr).equals(obj)) && pos != ignoreThisSlot) { return pos; } } } return -1; } public Iterator getAll() { return getAllNotMatching(Collections.EMPTY_LIST); } public Iterator getAllNotMatching(Collection keysToRemove) { return new HashIndexSetIterator(keysToRemove, hashIndexSetProperties); } /** * Locates the index of <tt>obj</tt>. * * @param indexKey an <code>Object</code> value that represents the index key * @return Iterator over a collection of objects that match the key */ public Iterator get(Object indexKey) { return new HashIndexSetIterator(indexKey, hashIndexSetProperties); } /** * * @param set represents the array that all elements are stored in * @param index the array index location to store the object. This should be calculated by one of * the insertionIndex methods * @param newObject the object to add to the set * @return true if object was added */ private boolean addObjectToSet(Object[] set, int index, Object newObject) { boolean added = true; if (index < 0) { throw new ArrayIndexOutOfBoundsException( "Cannot add:" + newObject + " into array position:" + index); } Object oldObject = set[index]; if (oldObject == null || oldObject == REMOVED) { set[index] = newObject; } return added; } /** * Unsupported, we do not use HashIndexSet as a general all purpose set */ @Override public synchronized boolean add(Object obj) { throw new UnsupportedOperationException( "add(Object) not supported, try add(Object key, Object obj) instead"); } /** * Add an object using the hash value of the provided indexKey * * @param obj the object to add * @return true if object has been added */ public synchronized int add(Object indexKey, Object obj) throws TypeMismatchException { if (indexKey == null) { indexKey = IndexManager.NULL; } // Note we cannot make the below optimization for hash index. Due to in place modification // where old key == new key (when no reverse map) we end up not updating to the correct slot in // this case // If oldKey and the newKey are same there is no need to update the // index-maps. // if ((oldKey == null && indexKey == null) // || indexKey.equals(oldKey)) { // return false; // } // grow/shrink capacity if needed preInsertHook(); HashIndexSetProperties metaData = hashIndexSetProperties; int indexSlot = insertionIndex(indexKey, metaData); Object old = metaData.set[indexSlot]; addObjectToSet(metaData.set, indexSlot, obj); hashIndexSetProperties = metaData; // only call this now if we are adding to an actual empty slot, otherwise we // have reused // and inserted into a set or array postInsertHook(old == null); return indexSlot; // yes, we added something } /** * Locates the next available insertion index for the provided indexKey and set * * @return the index of an open or resused position */ protected int insertionIndex(Object indexKey, HashIndexSetProperties metaData) { int hash; int pos; int mask = metaData.mask; Object curr; final Object[] array = metaData.set; hash = computeHash(indexKey); long start = -1L; if (cacheStats != null) { start = cacheStats.getTime(); cacheStats.incQueryResultsHashCollisions(); } try { /* * Code originated from fastutils Copyright (C) 2002-2014 Sebastiano Vigna * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ if (!((curr = array[pos = (it.unimi.dsi.fastutil.HashCommon.mix(hash)) & mask]) == null || curr == REMOVED)) { while (!((curr = array[pos = (pos + 1) & mask]) == null || curr == REMOVED)) { } } return pos; } finally { if (cacheStats != null) { cacheStats.endQueryResultsHashCollisionProbe(start); } } } @Override public boolean equals(Object other) { if (!(other instanceof HashIndexSet)) { return false; } Set that = (Set) other; if (that.size() != size()) { return false; } return containsAll(that); } @Override public int hashCode() { int hash = 0; Object[] set = hashIndexSetProperties.set; for (int i = set.length; i-- > 0;) { if (set[i] != null && set[i] != REMOVED) { hash += set[i].hashCode(); } } return hash; } /** * Expands or contracts a set to the new specified n. * * @param newN the expected size */ protected void rehash(int newN) { HashIndexSetProperties metaData = hashIndexSetProperties; if (TEST_ALWAYS_REHASH) { Thread.yield(); } Object[] oldSet = metaData.set; int oldCapacity = oldSet.length; int mask = newN - 1; int _maxSize = computeMaxSize(newN, _loadFactor); Object[] newSet = new Object[newN + 1]; HashIndexSetProperties newHashIndexProperties = new HashIndexSetProperties(newSet, mask); newHashIndexProperties.size = metaData.size; newHashIndexProperties.free = hashIndexSetProperties.computeNumFree(); newHashIndexProperties.removedTokens = 0; newHashIndexProperties.n = newN; newHashIndexProperties.maxSize = _maxSize; for (int i = oldCapacity; i-- > 0;) { if (oldSet[i] != null && oldSet[i] != REMOVED) { Object o = oldSet[i]; Object key = _imqEvaluator.evaluateKey(o); if (key == null) { key = IndexManager.NULL; } int index = insertionIndex(key, newHashIndexProperties); if (index >= 0) { addObjectToSet(newHashIndexProperties.set, index, o); } } } hashIndexSetProperties = newHashIndexProperties; } /** * Unsupported as the hash index does not use this method call * * @return an <code>Object[]</code> value */ @Override public Object[] toArray() { throw new UnsupportedOperationException("toArray not yet supported"); } /** * Unsupported as the hash index does not use this method call * * @param a an <code>Object[]</code> value * @return an <code>Object[]</code> value */ @Override public Object[] toArray(Object[] a) { throw new UnsupportedOperationException("toArray(Object[] a) not yet supported"); } /** * Empties the set. */ @Override public void clear() { HashIndexSetProperties metaData = hashIndexSetProperties; metaData.size = 0; metaData.free = capacity(); metaData.removedTokens = 0; Object[] set = metaData.set; for (int i = set.length; i-- > 0;) { set[i] = null; } hashIndexSetProperties = metaData; } protected int capacity() { return hashIndexSetProperties.set.length; } @Override public boolean remove(Object obj) { return remove(_imqEvaluator.evaluateKey(obj), obj); } public synchronized boolean remove(Object key, Object obj) { return remove(key, obj, -1); } /** * * @param key assumed to not be null, rather needs to be NULL token * @param newIndexSlot if inplace modification occurs with out having a reversemap we end up * scanning the entire index. We want to remove the region entry from the index slot but * not the newly added (correct) slot. Rather only the "old/wrong" slot * @return true if object was removed, false otherwise */ public synchronized boolean remove(Object key, Object obj, int newIndexSlot) { int indexSlot = index(key, obj, newIndexSlot); boolean removed = false; // The check for newIndexSlot != indexSlot is incase of in place modification. // When inplace occurs, oldkey == newkey and we end up wiping out the "new key" slow rather // than the old key slot. Instead let's get to the else portion if (indexSlot >= 0 && indexSlot != newIndexSlot) { removed = removeAt(indexSlot); return removed; } else if (!IndexManager.isObjectModificationInplace()) { // object could not be found so it's possible there was an inplace modification HashIndexSetIterator iterator = (HashIndexSetIterator) getAll(); while (iterator.hasNext()) { Object indexedObject = iterator.next(); if (areObjectsEqual(indexedObject, obj) && iterator.currentObjectIndex() != newIndexSlot) { iterator.remove(); return true; } } } return false; } public boolean areObjectsEqual(Object o1, Object o2) { if (o1 == null) { return o2 == null; } try { return TypeUtils.compare(o1, o2, OQLLexerTokenTypes.TOK_EQ).equals(Boolean.TRUE); } catch (TypeMismatchException e) { return o1.equals(o2); } } /** * Creates an iterator over the values of the set. The iterator supports element deletion. * * @return an <code>Iterator</code> value */ @Override public Iterator iterator() { return getAll(); } /** * Determine if all of the elements in <tt>collection</tt> are present. * * @param collection a <code>Collection</code> value * @return true if all elements are present. */ @Override public boolean containsAll(Collection collection) { for (final Object o : collection) { if (!contains(o)) { return false; } } return true; } /** * Unsupported because type mismatch exception cannot be thrown from Set interface */ @Override public boolean addAll(Collection collection) { throw new UnsupportedOperationException("Add all not implemented"); } /** * Removes all of the elements in <tt>collection</tt> from the set. * * @param collection a <code>Collection</code> value * @return true if the set was modified by the remove all operation. */ @Override public boolean removeAll(Collection collection) { boolean changed = false; int size = collection.size(); Iterator it = collection.iterator(); while (size-- > 0) { if (remove(it.next())) { changed = true; } } return changed; } /** * Removes any values in the set which are not contained in <tt>collection</tt>. * * @param collection a <code>Collection</code> value * @return true if the set was modified by the retain all operation */ @Override public boolean retainAll(Collection collection) { boolean changed = false; int size = size(); Iterator it = iterator(); while (it.hasNext()) { Object object = it.next(); if (!collection.contains(object)) { it.remove(); changed = true; } } return changed; } @Override /* * return true if no elements exist in the array that are non null or REMOVED tokens */ public boolean isEmpty() { return 0 == hashIndexSetProperties.size; } /** * Returns the number of positions used in the backing array Is not a true representation of the * number of elements in the array as the array may contain REMOVED tokens * * @return an <code>int</code> value */ @Override public int size() { return hashIndexSetProperties.size; } /** * only used for query optimization. Instead of crawling the entire array doing matches let's just * return the size of the array as that is the worst case size */ public int size(Object indexKey) { return hashIndexSetProperties.size; } /** * Compress the backing array if possible */ public void compact() { trimToSize(hashIndexSetProperties.size); } public boolean trimToSize(final int n) { final int l = HashCommon.nextPowerOfTwo((int) Math.ceil(n / _loadFactor)); if (hashIndexSetProperties.n <= l) { return true; } try { rehash(l); } catch (OutOfMemoryError cantDoIt) { return false; } return true; } /** * Remove the object at <tt>index</tt>. * * @param index an <code>int</code> value */ protected boolean removeAt(int index) { Object cur; HashIndexSetProperties metaData = hashIndexSetProperties; cur = metaData.set[index]; if (cur == null || cur == REMOVED) { // nothing removed return false; } else { metaData.set[index] = REMOVED; metaData.size--; metaData.removedTokens++; hashIndexSetProperties = metaData; return true; } } /** * initializes this index set */ protected int setUp(final int expectedCapacity, final float loadFactor) { int n = arraySize(expectedCapacity, loadFactor); _loadFactor = loadFactor; int _maxSize = computeMaxSize(n, loadFactor); int mask = n - 1; Object[] set = new Object[n + 1]; HashIndexSetProperties metaData = new HashIndexSetProperties(set, mask); metaData.n = n; metaData.maxSize = _maxSize; hashIndexSetProperties = metaData; hashIndexSetProperties.free = hashIndexSetProperties.computeNumFree(); return n; } private int computeMaxSize(int n, float loadFactor) { return Math.min((int) Math.ceil(n * loadFactor), n - 1); } /** * After insert, allows for calculating metadata */ protected void postInsertHook(boolean usedFreeSlot) { if (usedFreeSlot) { hashIndexSetProperties.free--; } else { // we used a removeToken hashIndexSetProperties.removedTokens--; } hashIndexSetProperties.size++; } /** * Before inserting we can ensure we have capacity */ protected void preInsertHook() { if (hashIndexSetProperties.size > hashIndexSetProperties.maxSize || hashIndexSetProperties.free == 0 || TEST_ALWAYS_REHASH) { rehash(arraySize(hashIndexSetProperties.size + 1, _loadFactor)); computeMaxSize(capacity(), _loadFactor); hashIndexSetProperties.free = hashIndexSetProperties.computeNumFree(); } else if (hashIndexSetProperties.removedTokens > hashIndexSetProperties.maxSize * CONDITIONAL_REMOVED_TOKEN_REHASH_FACTOR) { compact(); } } private class HashIndexSetIterator implements Iterator { private Object keyToMatch; // objects at time of iterator creation private final Object[] objects; private int pos; private int prevPos; private Collection keysToRemove; private Object current; private int hash; private int mask; private int probe; private HashIndexSetIterator(Collection keysToRemove, HashIndexSetProperties metaData) { this.keysToRemove = keysToRemove; pos = 0; prevPos = 0; objects = metaData.set; current = objects[pos]; } private HashIndexSetIterator(Object keyToMatch, HashIndexSetProperties metaData) { this.keyToMatch = keyToMatch; objects = metaData.set; mask = metaData.mask; hash = computeHash(keyToMatch); pos = (it.unimi.dsi.fastutil.HashCommon.mix(hash)) & mask; prevPos = pos; current = objects[pos]; } private void setPos(int pos) { prevPos = this.pos; this.pos = pos; } @Override public boolean hasNext() { // For Not Equals we need to look in the entire set if (keysToRemove != null) { while (pos < objects.length) { current = objects[pos]; if (current == null || current.equals(REMOVED)) { // continue searching } else if (notMatchingAnyKeyToRemove(keysToRemove, current)) { return true; } setPos(pos + 1); } return false; } else { current = objects[pos]; // For Equals query while (current != null) { if (current != REMOVED) { if (objectMatchesIndexKey(keyToMatch, current)) { return true; } } // If this is not the correct collection, one that does not match the // key we are looking for, then continue our search setPos((pos + 1) & mask); current = objects[pos]; } } return false; } private boolean notMatchingAnyKeyToRemove(Collection keysToRemove, Object current) { for (final Object keyToMatch : keysToRemove) { if (objectMatchesIndexKey(keyToMatch, current)) { return false; } } return true; } @Override public Object next() throws NoSuchElementException { Object obj = current; if (keysToRemove != null) { // for Not equals we need to continue looking // so increment the index here setPos(pos + 1); } else { // advance the pointer setPos((pos + 1) & mask); } return obj; } int currentObjectIndex() { return prevPos; } @Override public void remove() { removeAt(currentObjectIndex()); } public boolean objectMatchesIndexKey(Object indexKey, Object o) { Object fieldValue = _imqEvaluator.evaluateKey(o); if (fieldValue == IndexManager.NULL && indexKey == IndexManager.NULL) { return true; } else { try { if (fieldValue instanceof PdxString) { if (indexKey instanceof String) { fieldValue = fieldValue.toString(); } } else if (indexKey instanceof PdxString) { if (fieldValue instanceof String) { fieldValue = new PdxString((String) fieldValue); } } return TypeUtils.compare(fieldValue, indexKey, OQLLexerTokenTypes.TOK_EQ) .equals(Boolean.TRUE); } catch (TypeMismatchException e) { return fieldValue.equals(indexKey); } } } } }
{ "content_hash": "ffb1181459fbad25a38e7d3c6f846b06", "timestamp": "", "source": "github", "line_count": 806, "max_line_length": 100, "avg_line_length": 29.203473945409428, "alnum_prop": 0.6467414393746282, "repo_name": "jdeppe-pivotal/geode", "id": "1ea22927ac21bf8b2fee717950100945201e9051", "size": "24327", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "geode-core/src/main/java/org/apache/geode/cache/query/internal/index/HashIndexSet.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "104031" }, { "name": "Dockerfile", "bytes": "15956" }, { "name": "Go", "bytes": "40709" }, { "name": "Groovy", "bytes": "41916" }, { "name": "HTML", "bytes": "4037680" }, { "name": "Java", "bytes": "33151406" }, { "name": "JavaScript", "bytes": "1780821" }, { "name": "Python", "bytes": "29801" }, { "name": "Ruby", "bytes": "1801" }, { "name": "SCSS", "bytes": "2677" }, { "name": "Shell", "bytes": "275617" } ], "symlink_target": "" }
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * CakePHP MyHtmlHelper * @author lucas */ namespace App\View\Helper; use Bootstrap\View\Helper\BootstrapHtmlHelper; class MyHtmlHelper extends BootstrapHtmlHelper { public function __construct(\Cake\View\View $view, array $config = []) { $this->_useFontAwesome = true; if (isset($config['useFontAwesome'])) { $this->_useFontAwesome = $config['useFontAwesome']; } $this->helpers[] = 'Number'; parent::__construct($view, $config); } public function statusLance($id) { $r = [ 0 => ['text' => __('Não aceito'), 'class' => 'danger'], 1 => ['text' => __('Agardando aceitação'), 'class' => 'info'], 2 => ['text' => __('Aceito'), 'class' => 'success'], ]; return $this->label($r[$id]['text'], $r[$id]['class']); } public function status($id) { $r = [ 0 => ['text' => __('Inativo'), 'class' => 'danger'], 1 => ['text' => __('Ativo'), 'class' => 'info'], 9 => ['text' => __('Excluido'), 'class' => 'success'], ]; return $this->label($r[$id]['text'], $r[$id]['class']); } public function statusTipoUser($id) { $r = [ 0 => ['text' => __('Administrador'), 'class' => 'primary'], 1 => ['text' => __('Cliente'), 'class' => 'info'], 2 => ['text' => __('Fornecedor'), 'class' => 'success'], ]; return $this->label($r[$id]['text'], $r[$id]['class']); } public function statusPagSeguro($id) { $r = [ 1 => ['text' => __('Aguardando pagamento'), 'title' => 'O comprador iniciou a transação, mas até o momento o PagSeguro não recebeu nenhuma informação sobre o pagamento.', 'class' => 'default'], 2 => ['text' => __('Em análise'), 'title' => 'O comprador optou por pagar com um cartão de crédito e o PagSeguro está analisando o risco da transação.', 'class' => 'info'], 3 => ['text' => __('Paga'), 'title' => 'A transação foi paga pelo comprador e o PagSeguro já recebeu uma confirmação da instituição financeira responsável pelo processamento.', 'class' => 'success'], 4 => ['text' => __('Disponível'), 'title' => 'A transação foi paga e chegou ao final de seu prazo de liberação sem ter sido retornada e sem que haja nenhuma disputa aberta.', 'class' => 'success'], 5 => ['text' => __('Em disputa'), 'title' => 'O comprador, dentro do prazo de liberação da transação, abriu uma disputa.', 'class' => 'warning'], 6 => ['text' => __('Devolvida'), 'title' => 'O valor da transação foi devolvido para o comprador.', 'class' => 'danger'], 7 => ['text' => __('Cancelada'), 'title' => 'A transação foi cancelada sem ter sido finalizada.', 'class' => 'danger'], 8 => ['text' => __('Chargeback debitado'), 'title' => 'O valor da transação foi devolvido para o comprador.', 'class' => 'danger'], 9 => ['text' => __('Em contestação'), 'title' => 'O comprador abriu uma solicitação de chargeback junto à operadora do cartão de crédito.', 'class' => 'warning'], ]; return $this->label($r[$id]['text'], $r[$id]['class'], ['title' => $r[$id]['title']]); } public function link($title, $url = null, array $options = array()) { $default = [ 'iconDirection' => 'left', 'class' => '', 'preserveUrl' => false, ]; $options = \Cake\Utility\Hash::merge($default, $options); if ($options['preserveUrl'] === true) { if (is_array($url)) { if (count($this->request->query)) { $url = array_merge(['?' => $this->request->query], $url); } } } if (!isset($options['icon'])) { if (isset($url['action'])) { switch ($url['action']) { case 'add': $title = $this->iconDirection($title, 'save', $options['iconDirection']); $options['class'] .= ' btn-success '; break; case 'edit': $title = $this->iconDirection($title, 'pencil', $options['iconDirection']); $options['class'] .= ' btn-warning '; break; case 'list': $title = $this->iconDirection($title, 'search', $options['iconDirection']); $options['class'] .= ' btn-primary '; break; case 'view': $title = $this->iconDirection($title, 'list', $options['iconDirection']); $options['class'] .= ' btn-info '; break; default: break; } } if (isset($options['onclick'])) { if ($url === '#') { $title = $this->iconDirection($title, 'trash-o', $options['iconDirection']); $options['class'] .= ' btn-danger '; } } $options['escape'] = false; $options['class'] .= ' btn btn-xs '; } if (isset($options['icon']) AND $options['icon'] !== false) { $title = $this->iconDirection($title, $options['icon'], $options['iconDirection']); $options['escape'] = false; unset($options['icon']); } return parent::link($title, $url, $options); } private function iconDirection($title, $icon, $direction) { if ($direction === 'left') { return $this->icon($icon) . ' ' . $title; } return $title . ' ' . $this->icon($icon); } public function simNao($id) { $r = [ 0 => ['text' => __('Não'), 'class' => 'danger'], 1 => ['text' => __('Sim'), 'class' => 'success'], ]; return $this->label($r[$id]['text'], $r[$id]['class']); } public function data($data) { return date('d/m/Y', strtotime($data)); } public function moeda($value, $options = []) { $currency = [ 'before' => 'R$ ', 'zero' => '0,00', 'places' => '2', 'precision' => '2', 'locale' => 'pt_BR', ]; $currency = \Cake\Utility\Hash::merge($currency, $options); return $this->Number->format($value, $currency); } public function porcentagem($value, $options = []) { $currency = [ 'before' => '', 'after' => '%', 'zero' => '00', 'places' => '2', 'precision' => '3', 'locale' => 'pt_BR', ]; $currency = \Cake\Utility\Hash::merge($currency, $options); return $this->Number->format($value, $currency); } public function dataHora($data) { return date('d/m/Y H:i:s', strtotime($data)); } public function mask($val, $mask) { $maskared = ''; $k = 0; for ($i = 0; $i <= strlen($mask) - 1; $i++) { if ($mask[$i] == '#') { if (isset($val[$k])) $maskared .= $val[$k++]; } else { if (isset($mask[$i])) $maskared .= $mask[$i]; } } return $maskared; } public function cpfCnpj($str) { $str = str_replace(array(' ', '.', '-', '/'), '', $str); if (strlen($str) == 14) { return $this->mask($str, '##.###.###/####-##'); } else if (strlen($str) == 11) { return $this->mask($str, '###.###.###-##'); } return $str; } /** * Mostrar uma data em tempo * * @param integer $dataHora Data e hora em timestamp, dd/mm/YYYY ou null para atual * @param string $limite null, caso não haja expiração ou então, forneça um tempo usando o formato inglês para strtotime: Ex: 1 year * @return string Descrição da data em tempo ex.: a 1 minuto, a 1 semana * @access public */ public function tempo($dataHora = null, $limite = '30 days') { $datetime1 = new \DateTime($dataHora); $datetime2 = new \DateTime(date('YmdHis')); $interval = $datetime1->diff($datetime2); if ($interval->y > 0) { return 'mais de 1 ano'; } else if ($interval->m > 0) { return 'mais de 1 mês'; } else if ($interval->d > 0) { return 'mais de 1 dia'; } else { return $interval->h . ($interval->h > 1 ? 'horas' : 'hora') . ' ' . $interval->i . ($interval->i > 1 ? 'minutos' : 'minuto') . ' e ' . $interval->s . ($interval->s > 1 ? 'segundos' : 'segundo'); } } }
{ "content_hash": "b3d3c083447e430511c3c37dbd68c4aa", "timestamp": "", "source": "github", "line_count": 228, "max_line_length": 211, "avg_line_length": 39.44736842105263, "alnum_prop": 0.47264843228819214, "repo_name": "lucasnpinheiro/Cobrancas", "id": "d97e7e59ca94aec46df27749b4a4af749624297f", "size": "9049", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/View/Helper/MyHtmlHelper.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "270" }, { "name": "Batchfile", "bytes": "955" }, { "name": "CSS", "bytes": "690914" }, { "name": "HTML", "bytes": "126973" }, { "name": "JavaScript", "bytes": "1989889" }, { "name": "PHP", "bytes": "281852" }, { "name": "Shell", "bytes": "1352" } ], "symlink_target": "" }
import os from django.core.management.base import BaseCommand from poetry.apps.corpus.models import Poem class Command(BaseCommand): help = 'Automatic markup dump for Django' def add_arguments(self, parser): parser.add_argument('--out', action='store', dest='out', default="", help='Output') def handle(self, *args, **options): output = options.get('out') with open(output, "w", encoding='utf-8') as f: content = '[' poems = [poem for poem in Poem.objects.all() if poem.count_manual_markups() != 0] markups = [] for poem in poems: for markup in poem.markups.all(): if markup.author != "Automatic": markups.append(markup) break print(len(markups)) for markup in markups: content += markup.text + "," content = content[:-1] + ']' f.write(content)
{ "content_hash": "aa8bb0094294965474143b8f0ed6823a", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 93, "avg_line_length": 35.225806451612904, "alnum_prop": 0.48717948717948717, "repo_name": "IlyaGusev/PoetryCorpus", "id": "1fa85471713deecdd060ab2fb59c15a4d2acf487", "size": "1117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "poetry/apps/corpus/management/commands/get_manual.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3253" }, { "name": "HTML", "bytes": "27479" }, { "name": "JavaScript", "bytes": "19411" }, { "name": "Python", "bytes": "96947" }, { "name": "Shell", "bytes": "1168" } ], "symlink_target": "" }
package rabbit.handler.convert; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import rabbit.util.SProperties; /** An image converter that runs an external program * to do the actual conversion. */ public class ExternalProcessConverter implements ImageConverter { private static final String STD_CONVERT = "/usr/bin/gm"; private static final String STD_CONVERT_ARGS = "convert -quality 10 -flatten $filename +profile \"*\" jpeg:$filename.c"; private final boolean canConvert; private final String convert; private final String convertArgs; private final Logger logger = Logger.getLogger (getClass ().getName ()); /** Create a new ExternalProcessConverter configured from the given * properties. * @param props the configuration for this converter */ public ExternalProcessConverter (SProperties props) { convert = props.getProperty ("convert", STD_CONVERT); convertArgs = props.getProperty ("convertargs", STD_CONVERT_ARGS); String conv = props.getProperty ("convert", STD_CONVERT); File f = new File (conv); if (!f.exists () || !f.isFile ()) { logger.warning ("convert -" + conv + "- not found, is your path correct?"); canConvert = false; } else { canConvert = true; } } public boolean canConvert () { return canConvert; } public void convertImage (File from, File to, String info) throws IOException { int idx; String entryName = from.getAbsolutePath (); String convargs = convertArgs; while ((idx = convargs.indexOf ("$filename")) > -1) { convargs = convargs.substring (0, idx) + entryName + convargs.substring (idx + "$filename".length()); } String command = convert + " " + convargs; logger.fine ("ImageHandler running: '" + command + "'"); Process ps = Runtime.getRuntime ().exec (command); try { ps.waitFor (); closeStreams (ps); int exitValue = ps.exitValue (); if (exitValue != 0) { logger.warning ("Bad conversion: " + entryName + ", got exit value: " + exitValue); throw new IOException ("failed to convert image, " + "exit value: " + exitValue + ", info: " + info); } } catch (InterruptedException e) { logger.warning ("Interupted during wait for: " + entryName); } } /** Close the streams to the external process. * @param ps the Process that did the image conversion * @throws IOException if close fails */ public void closeStreams (Process ps) throws IOException { ps.getInputStream ().close (); ps.getOutputStream ().close (); ps.getErrorStream ().close (); } }
{ "content_hash": "a4e38e3780cc97be5298b3f60694dc0c", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 77, "avg_line_length": 32.629629629629626, "alnum_prop": 0.6647748770336739, "repo_name": "curious-attempt-bunny/rabbit-http-proxy-fake-desktop-headers", "id": "c845d6d77a55e89d254b84f75c213e0caa6822a4", "size": "2643", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/rabbit/handler/convert/ExternalProcessConverter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "638100" } ], "symlink_target": "" }
#ifndef _SD_RENDER_UTIL_H_ #define _SD_RENDER_UTIL_H_ #include "FsMacros.h" #include "math/FsVector2.h" #include "graphics/FsColor.h" NS_FS_USE namespace SdRenderUtil { void drawLine(Vector2 start,Vector2 end,float width,Color c); void drawRectangle(Vector2 start,Vector2 end,Color c); void setProjectionMatrix(Matrix4* mat); }; #endif /*_SD_RENDER_UTIL_H_*/
{ "content_hash": "4dc63a86f43ff33555c57d77d4d32f27", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 62, "avg_line_length": 20.444444444444443, "alnum_prop": 0.7391304347826086, "repo_name": "NosicLin/FParticle-Designer", "id": "103021ada24f065321bddc80081b9b7d319e5535", "size": "368", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "FParticleDesigner/src/util/SdRenderUtil.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "427" }, { "name": "C++", "bytes": "94481" }, { "name": "Prolog", "bytes": "2704" } ], "symlink_target": "" }